1.将数据存储为txt:
(1).写入
title='this is a test sentence.'
with open('D:\\test.txt',"a+") as f:
f.write(title)
f.close()
output='\t'.join(['name','title','age','gender'])#两个单词之间加制表符
with open('D:\\testt.txt','a+')as f:
f.write(output)
f.close()
(2).读取
with open('D:\\test.txt',"r",encoding="utf-8") as f:
result=f.read()
f.close()
2.将数据存储在csv(可以与excell相转换
)中:
csv:一种文件格式,可以先创建一个excel表格(如下),另存为csv格式(用记事本打开,如下下);
(1).读取
源码:
import csv
with open("D:\\test.csv",'r',encoding='utf-8-sig')as csvfile:
csv_reader=csv.reader(csvfile)
for row in csv_reader:
print(row)
输出:
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd']
(2).写入
importc csv
output_list=[‘1’,‘2’,‘3’,‘4’]
with open(‘D:\testt.csv’,‘a+’,encoding=‘utf-8-sig’,newline=’’) as csvfile:
w=csv.writer(csvfile)
w.writerow(output_list)