大家好,谢谢你的阅读。我正在尝试创建一个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
我正在尝试创建一个只有
的新csvSong_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。我做错了什么?
答案 0 :(得分:2)
你可以使用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
答案 1 :(得分:1)
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]])