tomtom tomtom - 4 months ago 15
Python Question

parse txt file to 2 csv files

Hi I already have working code for parsing

*.txt
with such pattern:

...
0.00001
0.00280
0.00022
...


into
*.csv
file

I do it with this:

in_txt = csv.reader(open(txt_file, "rb"), delimiter = '\n')
f = open(csv_file, 'wb')
out_csv = csv.writer(f)
out_csv.writerows(in_txt)
f.close()


I need help with modifying it to be able to parse the following pattern:

...
0.00001@0.02234
0.00280@0.00001
0.00022@0.03992
...


into 2 *.csv files (first with the first "column", second with the second "column")

Answer

A tested example:

import csv, os

txt_file = '/path/to/in.txt'
in_txt = csv.reader(open(txt_file, 'rb'), delimiter='@')
out_file1 = '/path/to/out1.txt'
out_file2 = '/path/to/out2.txt'
with open(out_file1, 'wb') as fou1, open(out_file2, 'wb') as fou2:
    for one, two in in_txt:
        fou1.write(one + os.linesep)
        fou2.write(two + os.linesep)