【问题标题】:Python printing certain columns from .csvPython从.csv打印某些列
【发布时间】:2014-10-28 22:06:56
【问题描述】:

大家好,感谢您的阅读。我正在尝试创建一个 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。我做错了什么?

【问题讨论】:

  • 我尝试了您的解决方案,它对我有用。 @inspectorG4dget 的回答更快,但没有修复代码中的任何错误。

标签: python csv export-to-csv


【解决方案1】:

您可以使用 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

【讨论】:

    【解决方案2】:
    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]])
    

    【讨论】:

      猜你喜欢
      • 2018-10-21
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-19
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多