簡體   English   中英

Python從.csv打印某些列

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM