0403CSV
CSV(Comma-Separated Values)文件存储(p134)
存储
1.列名和数据行分开写入
1
2
3
4
5
6
7
8
9
10
import csv
with open('data.csv', 'w') as file:
writer = csv.writer(file) #默认以逗号分隔,修改分隔符 delimiter=' '
#①.单行写入
writer.writerow(['id', 'name', 'age'])
writer.writerow(['10001', 'Mike', 20])
#②.多行写入
#writer.writerows([['10001', 'Mike', 20], ['10002', 'Bob', 22]])
2.结构化(字典)写入
1
2
3
4
5
6
7
import csv
with open('data.csv', 'w') as file:
writer = csv.DictWriter(file, fieldnames = ['id', 'name', 'age'] )
writer.writeheader()
writer.writerow({'id': '10001', 'name': 'Mike', 'age': 20})
writer.writerow({'id': '10002', 'name': 'Bob', 'age': 22})
3.pandas
库
1
2
3
4
5
6
#pip3 install pandas
data = [{'id': '10001', 'name': 'Mike', 'age': 20},
{'id': '10002', 'name': 'Bob', 'age': 22},
{'id': '10003', 'name': 'Jordan', 'age': 21},]
df = pd.DataFrame(data)
df.to_csv('data.csv', index=False)
读取
1.csv
库读取
1
2
3
4
5
import csv
with open('data.csv', 'r', encoding='utf-8') as file:
reader = csv.reader(file)
for row in reader:
print(row)
2.pandas
库读取
1
2
3
4
5
6
7
8
import pandas as pd
df = pd.read_csv('data.csv')
#①.迭代
for i, row in df.iterrows():
print(row.tolist())
##②.所有数据转换成list
#data = df.values.tolist()
This post is licensed under CC BY 4.0 by the author.