Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format txt file in Python

I am trying to convert a txt file into a csv file in Python. The current format of the txt file are several strings separated by spaces. I would like to write each string into one cell in the csv file.

The txt file has got following structure:

UserID Desktop Display (Version) (Server/Port handle), Date

UserID Desktop Display (Version) (Server/Port handle), Date

etc.

My approach would be following:

with open('licfile.txt', "r+") as in_file:
    stripped = (line.strip() for line in in_file)
    lines = (line.split(" ") for line in stripped if line)

with open('licfile.csv', 'w') as out_file:
    writer = csv.writer(out_file)
    writer.writerow(('user', 'desktop', 'display', 'version', 'server', 'handle', 'date'))
    writer.writerows(lines)

Unfortunately this is not working as expected. I do get following ValueError: I/O operation on closed file. Additionally only the intended row headers are shown in one cell in the csv file.

Any tips on how to proceed? Many thanks in advance.

like image 519
sim_rum Avatar asked Mar 19 '26 22:03

sim_rum


2 Answers

how about

with open('licfile.txt', 'r') as in_file, open('licfile.csv', 'w') as out_file:
    for line in in_file:
        if line.strip():
            out_file.write(line.strip().replace(' ', ',') + '\n')

and for the german Excel enthusiasts...

...
    ...
        ...
            ... .replace(' ', ';') + '\n')

:)

like image 67
SpghttCd Avatar answered Mar 21 '26 10:03

SpghttCd


You can also use the built in csv module to accomplish this easily:

import csv

with open('licfile.txt', 'r') as in_file, open('licfile.csv', 'w') as out_file:
    reader = csv.reader(in_file, delimiter=" ")  
    writer = csv.writer(out_file, lineterminator='\n')
    writer.writerows(reader)

I used lineterminator='\n' argument here as the default is \r\n and it ends up giving you an extra line of return per row in most cases.

There are also a few arguments you could use if say quoting is needed or a different delimiter is desired: https://docs.python.org/3/library/csv.html#csv-fmt-params

like image 35
r.ook Avatar answered Mar 21 '26 11:03

r.ook



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!