Reputation: 93
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?
Upvotes: 1
Views: 1147
Reputation: 2397
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
Upvotes: 2
Reputation: 113905
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]])
Upvotes: 1