lkv lkv - 3 months ago 17
Python Question

Python parsing multi column file

I have a file where i need to parse and construct in to a single row from multi row using python

NAME ID

TITLE DEP

USER1 0023

S1 SALES

USER2 0022

A2 ACCOUNT


As you can see here the file header are NAME, ID, TITLE, DEP

I want to print output like below so i can read easy in csv file and do other stuff easily.

NAME, ID, TITLE, DEP
USER1,0023,S1,SALES
USER2,0022,A2,ACCOUNT


Below is the code i started with but not able to get to where i want.
I tried with different options to split and replace but did not worked.

import csv
file =open('test_file_parse.csv','r')
out_file=open('test_out.csv','w')
lines = file.readlines()
file.close()
for line in lines:
line=line.strip()
print (line)


Any help is appreciated

Answer

Having all the words in a file called file.txt here is the code:


# read all the words
with open('file.txt') as f:
    words = f.read().split()

# convert to groups of 4-s
groups4 = [words[i:i+4] for i in range(0, len(words), 4)]

# convert to lines with commas using join()
lines = [', '.join(lst) for lst in groups4]

# and here is the result
for line in lines:
    print(line)

Output:

NAME, ID, TITLE, DEP
USER1, 0023, S1, SALES
USER2, 0022, A2, ACCOUNT
Comments