python读写csv
时间: 2023-10-24 07:10:03 浏览: 96
我们可以使用Python内置的csv模块来读写csv文件。具体步骤如下:
1. 导入csv模块:`import csv`
2. 打开csv文件:`with open('file.csv', newline='') as csvfile:`
- newline=''表示打开文件时不处理换行符,通常都要加上这个参数
3. 创建csv.reader对象:`reader = csv.reader(csvfile)`
4. 读取数据:`data = [row for row in reader]`
5. 关闭文件:`csvfile.close()`
写入csv文件同理,只需要使用csv.writer对象即可。
完整代码示例:
```python
import csv
# 读取csv文件
with open('file.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
data = [row for row in reader]
print(data)
# 写入csv文件
with open('new_file.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Name', 'Age', 'Gender'])
writer.writerow(['Alice', '25', 'Female'])
writer.writerow(['Bob', '30', 'Male'])
# 读取写入后的csv文件
with open('new_file.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
data = [row for row in reader]
print(data)
```
阅读全文