使用Python进行文件读写操作:详细案例
在Python中,文件的读写操作主要通过内置的open()
函数来完成。以下是一些详细的案例:
- 文件打开并读取:
```python打开文件,模式为’r’(只读)
with open(‘example.txt’, ‘r’) as file:逐行读取
for line in file:# 打印每行内容
print(line.strip()) # 确保移除行尾的换行符
关闭文件
file.close()
2. 文件写入:
```python
# 打开文件,模式为'w'(写入,覆盖已有的内容)
with open('example.txt', 'w') as file:
# 写入多行内容
file.write('Hello, World!\n')
file.write('This is an example.\n')
# 关闭文件
file.close()
- 文件追加(append):
```python打开文件,模式为’a’(追加,仅写入新内容)
with open(‘example.txt’, ‘a’) as file:追加多行内容
file.write(‘\nThis is an appended line.\n’)
关闭文件
file.close()
```
以上就是Python中进行文件读写操作的详细案例。
还没有评论,来说两句吧...