文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- [email protected] [DateTime(2004-09-19T22:05:29Z)] TableOfContents

描述

读取文件内容

Credit: Luther Blissett

问题

从文件读取文本或数据

解决

一次将文件内容读入一个长字符串的最简便方法

all_the_text = open('thefile.txt').read(  )    # 文本文件的全部文本
all_the_data = open('abinfile', 'rb').read(  ) # 2进制文件的全部数据

更好的方法是将文件对象和一个变量绑定,可以及时关闭文件。比如,读取文本文件内容:

file_object = open('thefile.txt')              # 打开文件
all_the_text = file_object.read(  )            # 文本文件的全部文本
file_object.close(  )                          # 使用完毕,关闭文件

将文本文件的全部内容按照分行 作为一个tuple读出有4种方法:

list_of_all_the_lines = file_object.readlines(  )             # 方法 1
list_of_all_the_lines = file_object.read(  ).splitlines(1)    # 方法 2
list_of_all_the_lines = file_object.read().splitlines(  )     # 方法 3 
list_of_all_the_lines = file_object.read(  ).split('\n')      # 方法 4 

方法1、2 返回的list中包含的string 元素末尾有'\n', 方法3、4 返回的list中包含的string元素末尾去掉了‘\n’.

方法1是效率最高的,而且最符合python的风格。

在Python 2.2以及更高版本中,有方法5和方法1等效

list_of_all_the_lines = list(file_object)                     # 方法 5 

讨论

如果文件大小不是特别大,那么一次将文件内容全部读出是最快的,一般来说对于以后文件内容的处理也是最方便的。

内置函数 open,打开文件并返回一个文件对象实例。 可以调用read方法读取文件内容(文本或2进制)到一个大字符串。

如果是文本内容,可以使用stringsplit方法或者特别的splitlines方法将此string分解成文本行的list

经常进行文件内容按行分解,可以直接调用文件对象的readlines方法,更方便更快捷。:)。

在Python 2.2以及更高版本中,可以直接将文件对象实例作为内置list函数的唯一参数。

在Unix 以及类Unix系统,比如Linux和BSD的各种变体中,文本文件和2进制文件没有实质的区别。

在Windows和Macintosh系统中,文本文件中的分行符不是标准的'\n'分隔符,分别是'\r\n'和'\r'。

打开文本文件时,Python会自动用'\n'替换相应的分隔符。

因此, 打开2进制文件不需要这种自动替换时,必须通知Python:

在类Unix平台上使用rb参数也没有什么坏处。 虽然不是必须的,但是区分文本文件和2进制文件是一个好习惯,可以使程序易于理解,同时具有较好的跨平台性。

You can call methods such as read directly on the file object produced by the open function, as shown in the first snippet of the solution. When you do this, as soon as the reading operation finishes, you no longer have a reference to the file object. In practice, Python notices the lack of a reference at once and immediately closes the file. However, it is better to bind a name to the result of open, so that you can call close yourself explicitly when you are done with the file. This ensures that the file stays open for as short a time as possible, even on platforms such as Jython and hypothetical future versions of Python on which more advanced garbage-collection mechanisms might delay the automatic closing that Python performs. ...

参考 See Also