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'。

 

猜你喜欢

转载自blog.csdn.net/ruibin_cao/article/details/84591268