Python 文件操作
文件操作的重要性
在编程中,我们经常需要读取文件中的数据或将数据写入文件。Python 提供了内置的函数来轻松处理文件操作。
打开文件
使用 open()
函数打开文件。它需要两个参数:文件名和模式。
常用的模式有:
'r'
: 读取 (默认模式)'w'
: 写入 (如果文件存在则覆盖,不存在则创建)'a'
: 追加 (如果文件存在则在末尾追加,不存在则创建)'x'
: 创建 (如果文件已存在则失败)'+'
: 更新 (读写)'b'
: 二进制模式't'
: 文本模式 (默认)
# 打开文件进行读取
try:
file = open("example.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("文件未找到!")
finally:
if 'file' in locals() and not file.closed:
file.close() # 始终关闭文件
使用 with
语句
with
语句可以确保文件在使用完毕后自动关闭,即使发生错误也是如此。这是推荐的文件操作方式。
try:
with open("example.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("文件 'example.txt' 未找到!")
# 写入文件
with open("output.txt", "w") as file:
file.write("这是第一行。\n")
file.write("这是第二行。\n")
# 追加到文件
with open("output.txt", "a") as file:
file.write("这是追加的一行。\n")
读取文件内容
有多种方法可以读取文件内容:
read(size)
: 读取指定数量的字节,如果未指定或为负,则读取整个文件。readline()
: 读取一行。readlines()
: 读取所有行并返回一个列表。
with open("output.txt", "r") as file:
print("--- 读取整个文件 ---")
print(file.read())
with open("output.txt", "r") as file:
print("\n--- 逐行读取 ---")
for line in file: # 迭代文件对象也是一种逐行读取的方式
print(line, end='') # end='' 防止打印额外的换行符
with open("output.txt", "r") as file:
print("\n\n--- 读取所有行到列表 ---")
lines = file.readlines()
print(lines)
for line in lines:
print(line.strip()) # strip() 去除首尾空白
文件操作是 Python 编程中一项基本且重要的技能。