mee mee mee mee - 6 months ago 17
Python Question

how to split a very long row data into two column by python (from txt file)

I have a txt file which has a very long row of datat (e.g as below)

234.45 234.3455 667.4556 566.3311 332.333 564.322 554.2564 21.203


I want to read that
.txt
file with python and want to split the data into two column as below:

234.45 234.3455
667.4556 566.3311
332.333 564.322
554.2564 21.203


I am new to python and I am not sure how to load the read .txt file and split the data into column? Anyone can help me? Thanks ahead.

Answer

Essentially you loop through every item and if the index of the item in the list is even you add to col1 and otherwise add to col2

This will work with items separated by any number of spaces

import re
with open("test.txt") as f:
    inputString = f.read()

#remove all extra spaces so all items separated by only one space
inputString = re.sub(r" +", " ", inputString)

itemsInString = inputString.split(" ")

col1 = []
col2 = []
for index, item in enumerate(itemsInString):
    if index % 2 == 0:
        col1.append(float(item))
    else:
        col2.append(float(item))

print(col1)
print(col2)

This gives you the following:
col1 = [234.45, 667.4556, 332.333, 554.2564]
col2 = [234.3455, 566.3311, 564.322, 21.203]

Writing it back out to a file:

writeString = ""
for item in zip(col1, col2):
    writeString += str(item[0]) + " " + str(item[1]) + "\n"

with open("outfile.txt", "w") as f:
    f.write(writeString)


And here's a more optimized way to write to file without string concatenation but it's less clear

with open("outfile.txt", "w") as f:
    f.write("\n".join(([" ".join([str(a[0]), str(a[1])]) for a in zip(col1, col2)])))