将list里的数据保存到CSV文件中,如果list文件中嵌套有list格式的数据,可以按照以下方式来处理:
给出示例代码:
import csv
lists = [[1,2,3],[4,5,6],[7,8,9]]
with open(filepath,"a+",newline='',encoding='utf-8-sig') as f: #不在出现空行
csv_writer = csv.writer(f)
for l in lists:
print(l)
csv_writer.writerow(l)
#list表的元素不能是int哦
dict类型保存到csv
headers=['moduleName', 'fileType', 'fileName', 'filePath', 'resourceId', 'textStr', 'translateStr']
m = [{'moduleName': 'lib_image_for_qzone', 'fileType': '.java', 'fileName': 'ImageTaskConst.java', 'filePath': '/lib_image_for_qzone/src/com/tencent/component/media/image/ImageTaskConst.java', 'resourceId': 'qqstr_1568118355604_595', 'textStr': '问题描述', 'translateStr': ''}, {'moduleName': 'lib_image_for_qzone', 'fileType': '.java', 'fileName': 'ImageTaskConst.java', 'filePath': '/lib_image_for_qzone/src/com/tencent/component/media/image/ImageTaskConst.java', 'resourceId': 'qqstr_1568118355604_706', 'textStr': '下载器未知错误', 'translateStr': ''}]
>>> new = []
>>> for i in m:
newdict = {}
newdict['textStr'] = i['textStr']
new.append(newdict)
with open('D:\\sss.csv','w') as f:
writer = csv.DictWriter(f, ['textStr'])
writer.writeheader()
for row in new:
writer.writerow(row)
另一种方法:
使用pandas dataframe
>>> import pandas as pd
>>> lists = [[1,2,3],[4,5,6],[7,8,9]]
>>> import numpy as np
>>> t = np.array(lists)
>>> t
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> data = pd.DataFrame(t)
>>> data
0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
>>> data.columns=['a','b','c']
>>> data
a b c
0 1 2 3
1 4 5 6
2 7 8 9
>>> data.to_csv("e:/test.csv")
网友评论