[英]Python printing certain columns from .csv
大家好,谢谢你的阅读。 我正在尝试创建一个python脚本,它将快速打印出我的.csv的某些列
数据库看起来像。
Song_Name,File_Name,Artist_Name,Artist_ID
Song1,filename1,artistname,artist001
Song1,filename1,artistname,artist001
Song1,filename1,artistname,artist001
Song1,filename1,artistname,artist001
我正在尝试创建一个只有的新csv
Song_Name,Artist_ID
Song1,artist001
Song1,artist001
Song1,artist001
Song1,artist001
我正在使用此代码:
import csv
with open('convert.csv','rb') as i:
with open('converted.csv','wb') as o:
r = csv.DictReader(i)
w = csv.DictWriter(o,'Song_Name Artist_ID'.split(),extrasaction='ignore')
w.writeheader()
for a in r:
w.writerow(a)
结果是一个标题为转换的银行.csv。 我究竟做错了什么?
您可以使用Python petl库(Python Extract Transform Load)假设您拥有csv文件中的第一个表(您也可以使用petl直接从数据库加载)。 然后你只需加载它并执行以下操作。
#Load the table
table1 = fromcsv('table1.csv')
# Alter the colums
table2 = cut(table1, 'Song_Name','Artist_ID')
#have a quick look to make sure things are ok. Prints a nicely formatted table to your console
print look(table2)
# Save to new file
tocsv(table2, 'new.csv')
快来看看这个简介: http : //petl.readthedocs.org/en/latest/case_study_1.html
with open('convert.csv','r') as infile, open('converted.csv','w') as outfile:
writer = csv.writer(outfile, delimiter=',')
for row in csv.reader(infile):
writer.writerow([row[0], row[-1]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.