Python文件对象的方法

146 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第 13 天,点击查看活动详情

要读取文件的内容,请调用f.read(size),它读取一定数量的数据并将其作为字符串返回。 size是一个可选的数字参数。当 size省略或为负时,将读取并返回文件的全部内容。否则,最多读取和返回size个字节。如果已到达文件末尾,f.read()将返回一个空字符串 ( "")。

>>> f.read()
'This is the entire file.\n'
>>> f.read()
''

f.readline()从文件中读取一行;换行符 ( \n) 留在字符串的末尾,如果文件不以换行符结尾,则仅在文件的最后一行省略。这使得返回值明确;如果f.readline()返回空字符串,则表示已到达文件末尾,而空行由 表示'\n',一个仅包含一个换行符的字符串。

>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''

要从文件中读取行,你可以循环遍历文件对象。这是内存高效,快速的,并简化代码:

>>> for line in f:
        print line,

This is the first line of the file.
Second line of the file

如果你想以列表的形式读取文件中的所有行,你也可以使用 list(f) 或 f.readlines()。 f.write(string)将字符串的内容写入文件,返回 None.

>>> f.write('This is a test\n')

要写入字符串以外的内容,需要先将其转换为字符串:

>>> value = ('the answer', 42)
>>> s = str(value)
>>> f.write(s)

f.tell()返回一个整数,给出文件对象在文件中的当前位置,以文件开头的字节为单位。要更改文件对象的位置,请使用. 位置是通过将偏移量添加到参考点来计算的;参考点由from_what参数选择。甲from_what从文件,1使用当前文件的开始位置0措施,和2名使用文件作为参考点的结束值。 from_what可以省略,默认为0,以文件开头为参考点。f.seek(offset, from_what)

>>> f = open('workfile', 'r+')
>>> f.write('0123456789abcdef')
>>> f.seek(5)      # Go to the 6th byte in the file
>>> f.read(1)
'5'
>>> f.seek(-3, 2)  # Go to the 3rd byte before the end
>>> f.read(1)
'd'

处理f.close()完文件后,调用关闭它并释放打开文件占用的所有系统资源。调用后f.close(),尝试使用文件对象将自动失败。

>>> f.close()
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file

**with在处理文件对象时使用关键字是一种很好的做法。**这样做的好处是文件在其套件完成后会被正确关闭,即使在途中引发异常也是如此。它也比编写等效的try-finally块要短得多:

>>> with open('workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

文件对象有一些额外的方法,例如 isatty() 和 truncate() ,它们使用频率较低。