码迷,mamicode.com
首页 > 编程语言 > 详细

Python csv模块使用方法

时间:2019-08-29 09:18:20      阅读:754      评论:0      收藏:0      [点我收藏+]

标签:head   time   names   pytho   encoding   表格   mes   open   for   

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()

 

Python csv模块使用方法

标签:head   time   names   pytho   encoding   表格   mes   open   for   

原文地址:https://www.cnblogs.com/guomeng888/p/11427589.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!