以下是一些常见的文件操作示例:
1. 打开文件利用 open() 函数可以打开一个文件,并返回一个文件工具。你可以指定模式(如读、写、追加等)和编码(如 UTF-8)。
# 打开文件用于读取(默认模式) file = open('example.txt', 'r', encoding='utf-8') # 打开文件用于写入(会覆盖文件内容) file = open('example.txt', 'w', encoding='utf-8') # 打开文件用于追加 file = open('example.txt', 'a', encoding='utf-8')
2. 读取文件
有几种方法可以读取文件内容:

# 读取全体文件内容 with open('example.txt', 'r', encoding='utf-8') as file: content = file.read() print(content) # 逐行读取文件内容 with open('example.txt', 'r', encoding='utf-8') as file: for line in file: print(line, end='') # end='' 用于避免多次换行
3. 写入文件
利用 write() 方法可以将字符串写入文件。
# 写入字符串到文件 with open('example.txt', 'w', encoding='utf-8') as file: file.write('Hello, World!\n') file.write('This is a new line.')
4. 追加文件
利用 'a' 模式可以在文件末端追加内容。
# 追加内容到文件末端 with open('example.txt', 'a', encoding='utf-8') as file: file.write('\nAppending a new line.')
5. 利用with语句
with 语句会自动管理文件的打开和关闭,纵然在读写过程中发生非常也会确保文件被精确关闭。
# 利用 with 语句打开文件 with open('example.txt', 'r', encoding='utf-8') as file: content = file.read() print(content) # 文件在 with 块结束时自动关闭
6. 检讨文件是否存在
在考试测验打开文件之前,可以利用 os.path.exists() 来检讨文件是否存在。
import os file_path = 'example.txt' if os.path.exists(file_path): print(f"{file_path} exists.") else: print(f"{file_path} does not exist.")
7. 删除文件
利用 os.remove() 可以删除文件。
import os file_path = 'example.txt' if os.path.exists(file_path): os.remove(file_path) print(f"{file_path} has been deleted.") else: print(f"{file_path} does not exist.")
8. 遍历目录
利用 os.listdir() 可以列出目录中的文件和子目录。
import os directory_path = '.' # 当前目录 for item in os.listdir(directory_path): print(item)
把稳事变文件路径:确保文件路径精确,如果路径中包含分外字符或空格,最好利用原始字符串(在字符串前加r)或双反斜杠(\\)。编码:在读取或写入文件时,指定精确的编码格式(如utf-8),以避免编码缺点。非常处理:可以利用try...except块来捕获文件操作中的非常,例如文件不存在、权限不敷等。