Python csv模块使用方法代码实例
这篇文章主要介绍了Pythoncsv模块使用方法代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
importcsv defopenSCV(filename): withopen("renting.csv",'r',encoding='utf_8_sig')asf: f_csv=csv.reader(f) forrowinf_csv: print(row) defTest1(): headers=['ID','NAME','Age','Height'] #表格内容 rows=[('1','LiLi',18,165),('2','Jack',20,170),('3','Marry',21,168)] withopen('test1.csv','w',encoding='utf_8_sig')ascsvfile: spamwriter=csv.writer(csvfile) spamwriter.writerow(headers) spamwriter.writerows(rows) defwriteDict(): withopen('test2.csv','w')ascsvfile: #创建字段名 fieldnames=['first_name','last_time'] #创建字段写入对象 writer=csv.DictWriter(csvfile,fieldnames=fieldnames) writer.writeheader() #写入表格内容 writer.writerow({'first_name':'Baked','last_time':'Beans'}) writer.writerow({'first_name':'Baked','last_time':'Beans'}) writer.writerow({'first_name':'Baked','last_time':'Beans'}) defreadDict(): withopen('test2.csv','r')ascsvfile: #读取文件 reader=csv.DictReader(csvfile) #遍历输入指定字段的内容 forrowinreader: print(row['first_name'],row['last_time']) if__name__=='__main__': Test1() writeDict() readDict()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。