1.txt文档的几种操作方法
1.1一般操作
f=open('data/txt/1.txt','a+',encoding='utf-8')
f.writelines('\n这是追加的一行文字')
f.close()
2.python专用方法
with open('data/txt/1.txt','r',encoding='utf-8') as f:
print(f.readlines()) #读取多行到一个列表中
输出:
f.readline() #一次读取一行
输出:
f.read() #一次读取全部
输出:
2.csv文件的操作
2.1方法一
读出
import csv
with open('data/csv/data01.csv','r',encoding='utf-8') as csvfile:
con=csv.reader(csvfile)
for i in con:
print(i)
创建,写入
import csv
headers = ['name', 'sex']
datas = [{'name':'aa', 'sex':23},
{'name':'bb', 'sex':44}
]
with open('data/csv/example.csv', 'w', newline='') as f:
writer = csv.DictWriter(f, headers)# 标头在这里传入,作为第一行数据
writer.writeheader()
for row in datas:
writer.writerow(row)
# 还可以写入多行
writer.writerows(datas)
2.2方法二
读取
import pandas as pd
f=pd.read_csv('data/csv/example.csv',encoding='utf-8')
f