简体   繁体   中英

Python printing certain columns from .csv

Hello everyone and thank you for reading. I am trying to create a python script that will quickly print out certain columns of my .csv

data base looks like.

Song_Name,File_Name,Artist_Name,Artist_ID
Song1,filename1,artistname,artist001
Song1,filename1,artistname,artist001
Song1,filename1,artistname,artist001
Song1,filename1,artistname,artist001

and I am trying to create a new csv that only has

Song_Name,Artist_ID
Song1,artist001
Song1,artist001
Song1,artist001
Song1,artist001

I am using this code:

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)

the result is a bank .csv titled converted. what am I doing wrong?

You could use the Python petl library (Python Extract Transform Load) Let's say you have the first table in a csv file (you can also load directly from the database using petl). Then you would simply load it and do the following.

#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')

Take a look at this quick intro: 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]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM