csv的追加写入
import csv
with open('data.csv', 'a') as csvfile:
fieldnames = ['id', 'name', 'age']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow({'id': '10004', 'name': 'Durant', 'age': 22})
指定编码格式
- 尝试写入中文的时候,没有使用encoding='utf-8',在文件中输出的是乱码,所以存在中文就要将编码格式添加上去
import csv
with open('data.csv', 'a', encoding='utf-8') as csvfile:
fieldnames = ['id', 'name', 'age']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow({'id': '10005', 'name': 'waws520', 'age': 22})
csv库读取csv文件
import csv
with open('data.csv', 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
"""
['id', 'name', 'age']
['10001', 'Mike', '20']
['10002', 'Bob', '22']
['10003', 'Jordan', '21']
['10004', 'Durant', '22']
['10005', 'waws520', '22']
"""
pandas读取csv文件
import pandas as pd
df = pd.read_csv('data.csv')
print(df)
"""
id name age
0 10001 Mike 20
1 10002 Bob 22
2 10003 Jordan 21
3 10004 Durant 22
4 10005 waws520 22
"""