在Python中,文件对象是通过open()
函数创建的,它用于读写文件。文件对象提供了一系列方法来操作文件,如读取、写入、关闭等。
文件对象的方法
-
open(filename, mode)
: 打开一个文件并返回一个文件对象。filename
是文件名,mode
是打开文件的模式,如'r'
表示只读,'w'
表示写入(如果文件已存在则清空内容),'a'
表示追加(在文件末尾添加内容),'r+'
表示读写等。 -
file.read([size])
: 读取文件内容。如果指定了size
参数,则读取指定数量的字节。 -
file.write(string)
: 将字符串写入文件。 -
file.close()
: 关闭文件。关闭后的文件不能再进行读写操作。 -
file.flush()
: 刷新文件缓冲区,确保所有待写入的数据都被写入文件。 -
file.readline()
: 读取文件的一行。 -
file.readlines()
: 读取文件的所有行,并返回一个包含每行作为元素的列表。 -
file.tell()
: 返回文件当前的位置(即文件的指针位置)。 -
file.seek(offset, whence)
: 改变文件当前的位置。offset
是偏移量,whence
指定起始位置,0表示文件开头,1表示当前位置,2表示文件末尾。 -
file.fileno()
: 返回文件的文件描述符(一个整数),通常用于底层文件操作。
示例
读取文件
python复制代码
# 打开文件并读取内容 | |
with open('example.txt', 'r') as file: | |
content = file.read() | |
print(content) | |
# 逐行读取文件 | |
with open('example.txt', 'r') as file: | |
for line in file: | |
print(line, end='') |
写入文件
python复制代码
# 写入文件 | |
with open('output.txt', 'w') as file: | |
file.write('Hello, World!\n') | |
file.write('This is a test.') | |
# 追加内容到文件 | |
with open('output.txt', 'a') as file: | |
file.write('\nAnother line appended.') |
读写文件
python复制代码
# 读写文件 | |
with open('readwrite.txt', 'r+') as file: | |
content = file.read() | |
print('Original content:', content) | |
# 移动文件指针到文件开头 | |
file.seek(0) | |
# 写入新内容 | |
file.write('New content at the beginning\n') | |
# 移动文件指针到文件末尾 | |
file.seek(0, 2) | |
# 追加新内容 | |
file.write('New content at the end\n') | |
# 读取修改后的文件内容 | |
with open('readwrite.txt', 'r') as file: | |
print('Modified content:', file.read()) |
关闭文件
虽然使用with
语句打开文件时,文件会在退出with
块时自动关闭,但显式关闭文件仍然是一个好习惯。
python复制代码
file = open('example.txt', 'r') | |
content = file.read() | |
file.close() # 关闭文件 |
注意:使用with
语句打开文件可以确保文件在使用完毕后被正确关闭,即使在处理文件时发生异常也是如此。因此,推荐总是使用with
语句来打开文件。