open()
返回 file object,最常用的参数有两个: open(filename, mode)
。
>>> f = open('workfile', 'w')
第一个实参是文件名字符串。第二个实参是包含描述文件使用方式字符的字符串。mode 的值包括 'r'
,表示文件只能读取;'w'
表示只能写入(现有同名文件会被覆盖);'a'
表示打开文件并追加内容,任何写入的数据会自动添加到文件末尾。'r+'
表示打开文件进行读写。mode 实参是可选的,省略时的默认值为 'r'
。
>>> with open('workfile') as f:
... read_data = f.read()
>>> # We can check that the file has been automatically closed.
>>> f.closed
True
如果没有使用 with
关键字,则应调用 f.close()
关闭文件,即可释放文件占用的系统资源。调用 f.write()
时,未使用 with
关键字,或未调用 f.close()
,即使程序正常退出,也**可能** 导致 f.write()
的参数没有完全写入磁盘。
通过 with 语句,或调用 f.close()
关闭文件对象后,再次使用该文件对象将会失败。
>>> f.close()
>>> f.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
文件对象的方法
f.read(size)
可用于读取文件内容,它会读取一些数据,并返回字符串(文本模式),或字节串对象(在二进制模式下)。 size 是可选的数值参数。省略 size 或 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, end='')
...
This is the first line of the file.
Second line of the file