File
Python 的文件 I/O 操作是处理文件读取、写入和管理的基本功能。以下是对 Python 文件 I/O 操作的详细介绍,包括常用方法和示例。可以方便地处理文本和二进制文件。使用 with
语句可以确保文件在使用后被正确关闭,增强代码的安全性和可读性。
1. 打开文件
使用 open()
函数打开文件。其基本语法如下:
python
file = open(file_path, mode)
1
- 参数:
file_path
: 文件的路径。mode
: 打开文件的模式。常用模式包括:'r'
: 只读模式(默认)。'w'
: 写入模式(会覆盖文件)。'a'
: 追加模式(在文件末尾添加内容)。'b'
: 二进制模式(如rb
或wb
)。'x'
: 独占写入模式(如果文件已存在,则引发错误)。
2. 读取文件
读取整个文件:
pythonwith open('file.txt', 'r') as file: content = file.read() print(content)
1
2
3逐行读取:
pythonwith open('file.txt', 'r') as file: for line in file: print(line.strip()) # strip() 去除行末换行符
1
2
3读取特定行数:
pythonwith open('file.txt', 'r') as file: lines = file.readlines() # 返回文件所有行的列表 print(lines[0]) # 输出第一行
1
2
3
3. 写入文件
写入字符串到文件:
pythonwith open('file.txt', 'w') as file: file.write('Hello, World!\n')
1
2追加内容到文件:
pythonwith open('file.txt', 'a') as file: file.write('Appending this line.\n')
1
2写入多个行:
pythonlines = ['Line 1\n', 'Line 2\n', 'Line 3\n'] with open('file.txt', 'w') as file: file.writelines(lines) # 写入多个行
1
2
3
4. 文件管理
关闭文件: 使用
with
语句可以自动关闭文件,避免忘记关闭。检查文件是否存在: 使用
os.path
模块中的exists()
方法。pythonimport os if os.path.exists('file.txt'): print('File exists.') else: print('File does not exist.')
1
2
3
4
5
6删除文件: 使用
os.remove()
删除文件。pythonimport os os.remove('file.txt') # 删除文件
1
2
3
5. 异常处理
在进行文件 I/O 操作时,建议使用异常处理来捕获可能的错误。
python
try:
with open('file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print('File not found.')
except IOError:
print('An error occurred while reading the file.')
1
2
3
4
5
6
7
2
3
4
5
6
7
示例
读取和写入文件的完整示例
python
# 写入文件
with open('example.txt', 'w') as file:
file.write('Hello, World!\n')
file.writelines(['Line 1\n', 'Line 2\n', 'Line 3\n'])
# 读取文件
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9