python csv文件处理
时间: 2023-10-08 14:06:55 浏览: 105
Python中处理CSV文件非常简单。下面是一些常用的CSV文件处理方法:
1. 读取CSV文件
```python
import csv
with open('file.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
```
2. 写入CSV文件
```python
import csv
with open('file.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age'])
writer.writerow(['John', '25'])
writer.writerow(['Mike', '30'])
```
3. 使用字典读取CSV文件
```python
import csv
with open('file.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
print(row['Name'], row['Age'])
```
4. 使用字典写入CSV文件
```python
import csv
with open('file.csv', 'w', newline='') as file:
fieldnames = ['Name', 'Age']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'Name': 'John', 'Age': '25'})
writer.writerow({'Name': 'Mike', 'Age': '30'})
```
这些方法可以帮助你在Python中处理CSV文件。
阅读全文
相关推荐












