0

I'm trying to convert a .txt file to a csv file using Python. This txt is not conventionnal (at least I have never seen something like that, it's basically like that: key a: foo key b: bar $$$ $$$ key a: foo1 key b: bar1 $$$ $$$ key a: foo2 key b: bar2

I simply want to get the following csv: foo, bar foo1, bar1 foo2, bar2

I have no difficulties to do that by simply going through the file as a string and by splitting, but I was wondering if there was a more elegant way to do that using existing libraries for instance. Thanks in advance!

LeGravier
  • 33
  • 5

1 Answers1

0

This is how I do it manually anyway:

with open('input.txt', 'r') as f:
    file_content = f.read()
raw_res = file_content.split('$$$\n$$$\n')

res = []

for item in raw_res:
    item_dict = {}
    keyvals = item.split('\n')
    for keyval in keyvals:
        if keyval != '' and ':' in keyval:
            key, val = keyval.split(':', 1)
            item_dict[key] = val.replace(",", " ") ## In order to ensure that val won't break the csv formatting later
    res.append(item_dict)
keys = res[0].keys
with open('output.csv', 'w') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(res)
LeGravier
  • 33
  • 5