将各种常见的数据类型写出到csv
持续更新…
预计收录:list(√)、dict(√)、numpy 等写出到csv
点击跳转~
1. 列表写出到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
2. 字典写出到csv
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
3. 字典数组写出到csv
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
小结:字典数组比嵌套列表更能保证数据可靠哦~
n. 补充: import json
1. 字典写出到 json
import json
with open('data.json', 'w', encoding='utf-8')as f:
# ensure_ascii=False 实现中文写入时 保存成中文
json.dump({'aa':'bb'}, f, ensure_ascii=False, indent=2)
1(逆). 从 json文件写到python
import json
with open('data.json', 'r', encoding='utf-8')as f:
data = json.load(f)
print(data) #{'aa': 'bb'}
# print(type(data)) #<class 'dict'>
2. 字典数组写出到 json
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,能将unicode字符(形如\uxxxx)显示为中文
# indent=5:缩进5,json展示更美观
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"
}
]
2(逆). json文件写入为python的字典数组类型
将data.json文件内容读到data_list(列表的每个元素为dict):
import json
with open("data.json","r") as f:
data_list = json.load(f)
print(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'}]