open()
是 Python 内置的一个函数,用于打开文件并返回一个文件对象。这个函数非常灵活,支持多种模式来控制文件的打开方式(如只读、写入等)。
pythonopen(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
'r'
(只读)。常用的模式包括:
'r'
:只读(默认)。文件必须存在。'w'
:写入。如果文件已存在,则覆盖;如果不存在,则创建新文件。'a'
:追加。如果文件存在,在文件末尾追加内容;如果不存在,则创建新文件。'x'
:独占创建。如果文件已存在则失败。'b'
:二进制模式(与上述模式结合使用,如 'rb'
或 'wb'
)。't'
:文本模式(默认)。'+'
:更新(读写)模式。python# 使用 with 语句自动管理文件关闭
with open('example.txt', 'r') as file:
content = file.read()
print(content)
如果你想逐行读取文件:
pythonwith open('example.txt', 'r') as file:
for line in file:
print(line.strip()) # 使用 strip() 去除行末换行符
python# 写入字符串到文件
with open('example.txt', 'w') as file:
file.write("Hello, World!\n")
# 追加内容到文件
with open('example.txt', 'a') as file:
file.write("Appending more text.\n")
python# 写入二进制数据
with open('example.bin', 'wb') as file:
file.write(b'\x00\x01\x02\x03')
# 读取二进制数据
with open('example.bin', 'rb') as file:
data = file.read()
print(data) # 输出: b'\x00\x01\x02\x03'
'utf-8'
。'strict'
, 'ignore'
, 'replace'
等。当处理文件时,可能会遇到各种异常情况,比如文件不存在、权限不足等。使用 try-except
结构可以帮助你优雅地处理这些异常:
pythontry:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found.")
except IOError as e:
print(f"An error occurred: {e}")