将各种常见的数据类型写出到csv
持续更新…
预计收录:list(√)、dict(√)、numpy 等写出到csv
import csv
data_list = [['John', 23, 'USA'],
['Jose', 44, 'Spain'],
['Anne', 29, 'UK'],
['Japan', 35, 'Lee']]
with open('data_list.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
for row in data_list:
writer.writerow(row)
data_list.csv内容
John,23,USA
Jose,44,Spain
Anne,29,UK
Japan,35,Lee
import csv
data = {'Name': 'John', 'Age': '23', 'Country': 'USA'}
with open('data.csv', 'w', newline='') as f:
writer = csv.writer(f)
for k, v in data.items():
writer.writerow([k, v])
data.csv 内容
Name,John
Age,23
Country,USA
import csv
labels = ['Name', 'Age', 'Country']
dct_arr = [
{'Name': 'John', 'Age': '23', 'Country': 'USA'},
{'Name': 'Jose', 'Age': '44', 'Country': 'Spain'},
{'Name': 'Anne', 'Age': '29', 'Country': 'UK'},
{'Name': 'Lee', 'Age': '35', 'Country': 'Japan'}
]
# 用异常处理来包装操作文件的代码,可以防止外部错误或关于文件写入过程的不兼容。
# 字典的kv对顺序可以与labels不一致,可以缺少,但不能有labels不存在的key
try:
with open('data_dict.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=labels)
writer.writeheader()
for elem in dct_arr:
writer.writerow(elem)
except IOError:
print("I/O error")
data_dict.csv 内容
Name,Age,Country
John,23,USA
Jose,44,Spain
Anne,29,UK
Lee,35,Japan
参考: 在 Python 中将字典写入 CSV
小结:字典数组比嵌套列表更能保证数据可靠哦~
import json
data_list = [
{'Name': 'John', 'Age': '23', 'Country': 'USA'},
{'Name': 'Jose', 'Age': '44', 'Country': 'Spain'},
{'Name': 'Anne', 'Age': '29', 'Country': 'UK'},
{'Name': 'Lee', 'Age': '35', 'Country': 'Japan'}
]
with open('data.json', 'w', encoding='utf-8')as f:
# ensure_ascii=False:不使用ascii,能显示中文; indent=5:缩进5
f.write(json.dumps(data_list, ensure_ascii=False, indent=5))
data.json内容:
[
{
"Name": "John",
"Age": "23",
"Country": "USA"
},
{
"Name": "Jose",
"Age": "44",
"Country": "Spain"
},
{
"Name": "Anne",
"Age": "29",
"Country": "UK"
},
{
"Name": "Lee",
"Age": "35",
"Country": "Japan"
}
]