在 Python 中,文件处理是一个常见的任务,主要包括文件的打开、读取、写入和关闭。以下是 Python 文件处理的基本操作方法:
- 打开文件:使用
open()
函数。 - 读取文件:使用
read()
,readline()
,readlines()
方法。 - 写入文件:使用
write()
,writelines()
方法。 - 关闭文件:使用
close()
方法,或者使用with
语句自动管理文件的关闭。
文件处理的基本操作
1. 打开文件
file = open('example.txt', 'r') # 以只读模式打开文件
2. 读取文件
-
读取整个文件内容:
content = file.read()
-
读取一行:
line = file.readline()
-
读取所有行:
lines = file.readlines()
3. 写入文件
-
写入字符串:
file = open('example.txt', 'w') # 以写模式打开文件 file.write('Hello, World!')
-
写入多行:
lines = ['First line\n', 'Second line\n', 'Third line\n'] file.writelines(lines)
4. 关闭文件
file.close()
使用 with
语句
with
语句可以自动管理文件的打开和关闭,推荐使用这种方式。
with open('example.txt', 'r') as file:
content = file.read()
完整的代码示例
import os
# 写入文件示例
def write_to_file(file_path, content):
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content)
print(f"Content written to {file_path}")
# 读取文件示例
def read_from_file(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
print(f"Content read from {file_path}:\n{content}")
return content
# 追加写入文件示例
def append_to_file(file_path, content):
with open(file_path, 'a', encoding='utf-8') as file:
file.write(content)
print(f"Content appended to {file_path}")
# 示例文件路径
file_path = 'example.txt'
# 写入内容
write_to_file(file_path, "Hello, World!\nThis is a test file.")
# 读取内容
read_from_file(file_path)
# 追加内容
append_to_file(file_path, "\nAppending a new line.")
# 再次读取内容
read_from_file(file_path)
# 删除示例文件
os.remove(file_path)
print(f"{file_path} has been deleted.")
总结
- 使用
open()
函数可以打开文件,指定模式如'r'
(只读)、'w'
(写入)、'a'
(追加)等。 - 使用
read()
,readline()
,readlines()
方法可以读取文件内容。 - 使用
write()
,writelines()
方法可以写入文件内容。 - 使用
close()
方法关闭文件,或者使用with
语句自动管理文件的关闭。