Python文件读写处理代码
时间: 2023-12-03 08:02:20 浏览: 107
【Python】文件读写操作代码
5星 · 资源好评率100%
读取文件:
```python
# 打开文件
file = open('file.txt', 'r')
# 读取整个文件
content = file.read()
# 读取一行
line = file.readline()
# 读取所有行
lines = file.readlines()
# 关闭文件
file.close()
```
写入文件:
```python
# 打开文件
file = open('file.txt', 'w')
# 写入内容
file.write('Hello World!')
# 关闭文件
file.close()
```
追加内容:
```python
# 打开文件
file = open('file.txt', 'a')
# 写入内容
file.write('Hello World!')
# 关闭文件
file.close()
```
处理CSV文件:
```python
import csv
# 读取CSV文件
with open('file.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
# 写入CSV文件
with open('file.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Name', 'Age'])
writer.writerow(['Alice', '25'])
writer.writerow(['Bob', '30'])
```
阅读全文