Python从.csv打印某些列

Python从.csv打印某些列,python,csv,export-to-csv,Python,Csv,Export To 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 我

大家好,谢谢你们的阅读。我正在尝试创建一个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
我正在尝试创建一个只有

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)

结果是一个标题为转换的bank.csv。我做错了什么?

您可以使用Python petl库(Python提取转换加载)
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]])
假设您拥有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')

看看这篇简短的介绍:

我尝试了你的解决方案,它对我有效@inspectorG4dget的答案更快,但不会修复代码中的任何错误。