一、TXT
subline = '字典:Python内置的数据结构之一,与列表一样是一个可变序列.'
with open('data.txt', 'a', encoding='utf-8') as fp:
fp.write(subline)
二、CSV
参考:
https://docs.python.org/zh-cn/3.7/library/csv.html
import csv
import os
# 通过可迭代对象写入
with open('data1.csv', 'w', encoding='utf-8-sig', newline='') as f: # 注意编码格式为 utf-8-sig,防止中文乱码,加上 newline 参数
writer = csv.writer(f) # 默认是以制表符为分隔符
# writer = csv.writer(f, delimiter=' ') # delimiter=' ':以空格为分隔符
if not os.path.getsize('data1.csv'): # 判断文件是否为空
writer.writerow(['名字', 'value', 'result'])
writer.writerow(['1', '2', 3])
writer.writerow(['a', 'b', 'c', 'd'])
writer.writerow([i for i in range(6)])
writer.writerows([[i for i in range(3)], ['I', 'am', '皮特']])
import csv
import os
# 通过字典写入
with open('data2.csv', 'w', encoding='utf-8-sig', newline='') as f: # 注意编码格式为 utf-8-sig,防止中文乱码,加上 newline 参数
fieldnames = ['id', 'name', 'age', 'sex']
writer = csv.DictWriter(f, fieldnames=fieldnames)
if not os.path.getsize('data2.csv'): # 判断文件是否为空
writer.writeheader()
writer.writerow({'id': '0', 'name': '洛水三千', 'age': 20})
writer.writerow({'id': 1, 'name': 'A', 'age': 11})
writer.writerow({'id': 2, 'name': 'B', 'age': 22, 'sex': '男孩'})
writer.writerows([{'id': '3', 'name': 'C', 'age': 42}, {'id': 4, 'name': 'D', 'age': 30},
{'id': 5, 'name': 'E', 'age': 2}])
三、XLSX
import openpyxl as xl
import os
def write_excel_file(folder_path):
result_path = os.path.join(folder_path, "my.xlsx")
print(result_path)
print('***** 开始写入excel文件 ' + result_path + ' ***** \n')
if os.path.exists(result_path):
print('***** excel已存在,在表后添加数据 ' + result_path + ' ***** \n')
workbook = xl.load_workbook(result_path)
else:
print('***** excel不存在,创建excel ' + result_path + ' ***** \n')
workbook = xl.Workbook()
workbook.save(result_path)
sheet = workbook.active
headers = ["URL", "predict", "score"]
sheet.append(headers)
result = [['1', 1, 1], ['2', 2, 2], ['3', 3, 3]]
for data in result:
sheet.append(data)
workbook.save(result_path)
print('***** 生成Excel文件 ' + result_path + ' ***** \n')
if __name__ == '__main__':
write_excel_file("D:\core\\")
四、JSON
import json
data_list = [{"name": 1, "age": 2, "sex": 3}, {"name": "a", "age": "b", "sex": "c"}, {"name": "临", "age": "兵", "sex": "斗"}]
with open('data3.json', 'w', encoding='utf-8')as file:
file.write(json.dumps(data_list, ensure_ascii=False, indent=2)) # ensure_ascii参数显示中文,indent参数缩进美化