python文件读写案例
时间: 2024-11-12 13:16:23 浏览: 3
在Python中,文件读写操作是非常常见的任务。以下是几个基本的案例:
**打开文件进行读取(read模式)**:
```python
# 打开文件(默认文本模式)
with open('example.txt', 'r') as file:
# 读取整个文件内容
content = file.read()
print(content)
```
**逐行读取(lines模式)**:
```python
with open('example.txt', 'r') as file:
for line in file:
print(line.strip()) # 去除行尾的换行符
```
**写入文件(write模式)**:
```python
content = 'Hello, World!'
with open('output.txt', 'w') as file:
file.write(content)
```
**追加内容到文件(append模式)**:
```python
with open('output.txt', 'a') as file:
file.write('\nThis is a new line.')
```
**处理异常**:
```python
try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found.")
```
阅读全文