How to delete columns in a CSV file?
Using a dict to grab headings then looping through gets you what you need cleanly.
import csv
ct = 0
cols_i_want = {'cost' : -1, 'date' : -1}
with open("file1.csv","rb") as source:
rdr = csv.reader( source )
with open("result","wb") as result:
wtr = csv.writer( result )
for row in rdr:
if ct == 0:
cc = 0
for col in row:
for ciw in cols_i_want:
if col == ciw:
cols_i_want[ciw] = cc
cc += 1
wtr.writerow( (row[cols_i_want['cost']], row[cols_i_want['date']]) )
ct += 1
Use of Pandas module will be much easier.
import pandas as pd
f=pd.read_csv("test.csv")
keep_col = ['day','month','lat','long']
new_f = f[keep_col]
new_f.to_csv("newFile.csv", index=False)
And here is short explanation:
>>>f=pd.read_csv("test.csv")
>>> f
day month year lat long
0 1 4 2001 45 120
1 2 4 2003 44 118
>>> keep_col = ['day','month','lat','long']
>>> f[keep_col]
day month lat long
0 1 4 45 120
1 2 4 44 118
>>>
import csv
with open("source","rb") as source:
rdr= csv.reader( source )
with open("result","wb") as result:
wtr= csv.writer( result )
for r in rdr:
wtr.writerow( (r[0], r[1], r[3], r[4]) )
BTW, the for
loop can be removed, but not really simplified.
in_iter= ( (r[0], r[1], r[3], r[4]) for r in rdr )
wtr.writerows( in_iter )
Also, you can stick in a hyper-literal way to the requirements to delete a column. I find this to be a bad policy in general because it doesn't apply to removing more than one column. When you try to remove the second, you discover that the positions have all shifted and the resulting row isn't obvious. But for one column only, this works.
del r[2]
wtr.writerow( r )
You can directly delete the column with just
del variable_name['year']