Python讀寫文件小結

read()、readline()、readlines()的比較

read

特點是:讀取整個文件,將文件內容放到一個字符串變量中。

劣勢是:如果文件非常大,尤其是大於內存時,無法使用read()方法。

read()的返回值是字符串,讀取的是整個文件,包含文件中的換行符。

readline

特點:readline()方法每次讀取一行;返回的是一個字符串對象,保持當前行的內存

缺點:比readlines慢得多

readlinede()的返回值也是字符串,每次讀取一行,也包含這一行的換行符。

readlines

特點:一次性讀取整個文件;自動將文件內容分析成一個行的列表

比readline要快,其返回值是一個列表,列表的元素是文件中包含換行符的一行字符串。

 

try……finally與with……as的比較

讀寫文件的正確方式是:打開一個文件後,一定要關閉文件。最簡陋的做法是:

F = open('文件', 'r')
.
.
.
F.close()

爲什麼說他簡陋呢,因爲如果要讀取文件失敗,或者其他異常發生,則無法關閉文件,造成內存泄露。

於是有這麼做的:

 f = open('azusa', 'r') 
  try: 
    print ''.join(f.readlines()) 
  finally: 
    f.close()

但是這樣寫起來比較繁瑣,用with……as就好很多:

 with open('azusa', 'r') as f
    print ''.join(f.readlines()) 
  

有時候需要用到異常捕獲,使用try……finally的寫法:

 
   try: 
    f = open('sawako', 'r') 
    try: 
      print ''.join(f.readlines()) 
    finally: 
      f.close() 
   except: 
     print 'error occurs while reading file'

with……as是這樣的:

 try: 
     with open('mio', 'r') as f: 
      print ''.join(f.readlines()) 
  except: 
    print 'error occurs while reading file'

反正就是要簡單。

write、writelines和numpy.savetxt的比較

保存數據到文件中去,其實尋常數據用write、writelines就可以了,但是對於需要做簡單處理,然後保存的方法採用numpy的savetxt要好用很多。

write()

需要傳入一個字符串做爲參數,否則會報錯。

writelines()

writelines()既可以傳入字符串又可以傳入一個字符序列,並將該字符序列寫入文件,但是必須傳入的是字符序列,不能是數字序列。所以在用writelines保存數字時,還需要做轉換。太費勁了!!!

numpy.savetxt()

 

savetxt的函數原型是:

numpy.savetxt(fnameXfmt='%.18e'delimiter=' 'newline='\n'header=''footer=''comments='# 'encoding=None)

fname : filename or file handle
If the filename ends in .gz, the file is automatically saved in compressed gzip format. loadtxt understands gzipped files transparently.

X : 1D or 2D array_like
Data to be saved to a text file.

fmt : str or sequence of strs, optional
A single format (%10.5f), a sequence of formats, or a multi-format string, e.g. ‘Iteration %d – %10.5f’, in which case delimiter is ignored. For complex X, the legal options for fmt are:

a single specifier, fmt=’%.4e’, resulting in numbers formatted like ‘ (%s+%sj)’ % (fmt, fmt)
a full string specifying every real and imaginary part, e.g. ‘ %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej’ for 3 columns
a list of specifiers, one per column - in this case, the real and imaginary part must have separate specifiers, e.g. [‘%.3e + %.3ej’, ‘(%.15e%+.15ej)’] for 2 columns
delimiter : str, optional
String or character separating columns.

newline : str, optional
String or character separating lines.

New in version 1.5.0.

header : str, optional
String that will be written at the beginning of the file.

New in version 1.7.0.

footer : str, optional
String that will be written at the end of the file.

New in version 1.7.0.

comments : str, optional
String that will be prepended to the header and footer strings, to mark them as comments. Default: ‘# ‘, as expected by e.g. numpy.loadtxt.

New in version 1.7.0.

encoding : {None, str}, optional
Encoding used to encode the outputfile. Does not apply to output streams. If the encoding is something other than ‘bytes’ or ‘latin1’ you will not be able to load the file in NumPy versions < 1.14. Default is ‘latin1’.

New in version 1.14.0.

其中參數fname是文件名,X是需要保存的一維或二維數組,這兩個是必須的。只指定這兩個參數,保存的數據是科學計數法的,而且用18位,這就很煩人。添加fmt參數即可:fmt='%s'。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章