[Python] CSV操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hitwangpeng/article/details/68489123

一、csv的reader()读取操作

#encoding=utf-8
import sys,os
import csv

def main():
	fobj = open("readtest.csv","rb+")
	read_f = csv.reader(fobj)
	for eachline in read_f:
		print eachline
        fobj.close()
if __name__=="__main__":
	main()



二、csv的writer()写操作

#encoding=utf-8
import sys,os
import csv

def main():
	fobj = open("writetest.csv","wb+")
	write_f = csv.writer(fobj)
	title_list = " ".join(['Name','University','Major']).decode("utf8").encode("gb2312").split()
	write_f.writerow(title_list)
	
	data = [
	('wangpeng','HIT','Information Security'),
	('zhangsan','THU','Computer Science and Technology'),
	('lisi','PKU','Software Engineering')
	]
	
	write_f.writerows(data)
	fobj.close()

if __name__=="__main__":
	main()


三、csv的DictReader()读操作

#encoding=utf-8
import sys,os
import csv

def main():
	fobj = open('readtest.csv','rb+')
	reader = csv.DictReader(fobj)
	
	for row in reader:
		if row['Name'] == 'wangpeng':
			print row

if __name__=="__main__":
	main()

四、csv的DictWriter()写操作

#encoding=utf-8
import sys,os
import csv

def main():
	fobj = open('test.csv','wb+')
	title_name = ['first_name','last_name']
	writer = csv.DictWriter(fobj,fieldnames = title_name)

	writer.writeheader()
	writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
	writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
	writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
	
if __name__=="__main__":
	main()


博主设置当前文章不允许评论。

没有更多推荐了,返回首页