这篇文章主要介绍了Python csv模块使用方法代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

import csv
def openSCV(filename):
  with open("renting.csv",'r',encoding = 'utf_8_sig') as f:
    f_csv = csv.reader(f)
    for row in f_csv:
      print(row)
def Test1():
  headers = ['ID','NAME','Age','Height']
  #表格内容
  rows = [('1','LiLi',18,165),('2','Jack',20,170),('3','Marry',21,168)]
  with open('test1.csv','w',encoding='utf_8_sig') as csvfile:
    spamwriter = csv.writer(csvfile)
    spamwriter.writerow(headers)
    spamwriter.writerows(rows)
def writeDict():
  with open('test2.csv','w') as csvfile:
    #创建字段名
    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'})
def readDict():
  with open('test2.csv','r') as csvfile:
    #读取文件
    reader = csv.DictReader(csvfile)
    #遍历输入指定字段的内容
    for row in reader:
      print(row['first_name'],row['last_time'])
if __name__ == '__main__':
  Test1()
  writeDict()
  readDict()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com