Reputation: 724
Is there a way to use the python csv module to save a csv which has two columns of the same name?
This is my function
def DictListToCsv(Data, FileName, FieldNames):
with open(FileName, 'w') as f:
writer = csv.DictWriter(f, fieldnames = FieldNames, dialect = 'excel', delimiter=',', lineterminator='\n')
writer.writeheader()
writer.writerows(Data)
Every approach i try would involve at some point having a dictionary with two headers named the same, which is of course not possible
Upvotes: 3
Views: 1901
Reputation: 500
Will this work for you? [update] setting now the delimiter and line terminator
def DictListToCsv(Data, FileName, FieldNames):
with open(FileName, 'w') as f:
writer = csv.writer(f, dialect = 'excel', delimiter=',', lineterminator='\n')
writer.writerow(FieldNames)
writer.writerows(Data)
FieldNames = ['Spam','Spam','Spam','Spam','more Spam']
Data = [[11,12,13,14,15],[21,22,23,24,25]]
DictListToCsv(Data, 'eggs.csv', FieldNames)
Upvotes: 0
Reputation: 1006
Have you tried using pandas module ? Convert your data into pandas dataframe ("df") and then use :
df.columns=['x','x']
and finally, save it to a csv file :
df.to_csv(r'/home/ishan/Desktop/a.csv',header=True, index=False)
it will work.
Upvotes: 2