1.Python处理csv文件之csv.writer()
import csv
def csv_write(path,data):
with open(path,'w',encoding='utf-8',newline='') as f:
writer = csv.writer(f,dialect='excel')
for row in data:
writer.writerow(row)
return True
调用上面的函数
data = [
['Name','Height'],
['Keys','176cm'],
['HongPing','160cm'],
['WenChao','176cm']
]
csv_write('test.csv',data)
运行结果
2.Python处理csv文件之csv.reader()
def csv_read(path):
data = []
with open(path,'r',encoding='utf-8') as f:
reader = csv.reader(f,dialect='excel')
for row in reader:
data.append(row)
return data
调用上面的函数
data = csv_read('test.csv')
print(data)
运行结果
[['Name', 'Height'], ['Keys', '176cm'], ['HongPing', '160cm'], ['WenChao', '176cm']]
3.Python处理csv文件之csv.DictWriter()
def csv_dict_write(path,head,data):
with open(path,'w',encoding='utf-8',newline='') as f:
writer = csv.DictWriter(f,head)
writer.writeheader()
writer.writerows(data)
return True
调用上面的函数
head = ['Name','Age']
data = [
{'Name':'Keys', 'Age':28},
{'Name':'HongPing', 'Age':29},
{'Name':'WenChao', 'Age':15}
]
csv_dict_write('test2.csv',head,data)
运行结果
4.Python处理csv文件之csv.DictReader()
def csv_dict_read(path):
with open(path,'r',encoding='utf-8') as f:
reader = csv.DictReader(f,dialect='excel')
for row in reader:
print(row['Name'])
调用上面的函数
csv_dict_read('test2.csv')
运行结果
Keys
HongPing
WenChao