I need to ouput a list of dicts in python to a csv file. But I wanted to split them by filename. I have a list of dicts that looks like this:
{'Filename': 'F:\\Desktop\\Metadata\informationtechnologies1.pdf',
'DESCRIPTION': [u'This is a test sentence.'],
'NAME': [u'This is a test name'],
'PERIOD': [],
'INFO2': [u'TEST1',
u'TEST2',
u'TEST3',
u'TEST4',
u'TEST5',],
'INFO': [u'TEST6',
u'TEST7',
u'TEST8',
u'TEST9',
u'TEST10',
u'TEST11',]},
{'Filename': 'F:\\Desktop\informationtechnologies.pdf',
I need to print these exactly how it appears in a single column, with the results being in a new row. Preferably a new line after each filename to separate all the results. For example:
Filename: informationtechnologies1.pdf DESCRIPTION: This is a sentence INFO2: TEST2 TEST3 TEST4 TEST5
Filename:informationtechnologies.pdf
I have tried the following code but it places it each list into single columns(one column can have a list of 20 pieces of data in the info columns):
df = DataFrame.from_dict(results)
df.to_csv("F:\Desktop/meta.csv",encoding='utf-8')
I need the data to be all iterated in column 1, so if there is a list within a dict I want each item in that list to print on a new line
What you show is not a csv file but a plain text file.
Assuming your requirements are:
Filename
print on first line the key, a colon, a space and the value I would use explicit loops and tests, because I do not know any tool that does this out of the box:
with open("F:\\Desktop/meta.csv", "w") as fd:
for d in results:
if 'Filename' in d:
dummy = fd.write('Filename: ' + d['Filename'] + '\n')
for k, l in d.iteritems():
if k != 'Filename':
dummy = fd.write(k + ':\n')
if isinstance(l, list):
for item in l:
dummy = fd.write(item.encode('utf8') + '\n')
else:
dummy = fd.write(unicode(l).encode('utf8') + '\n')
dummy = fd.write('\n')
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.