简体   繁体   中英

Python Write Groups to Coloumns

I have managed to create a text file of values which I need to write to either csv or xlsx. Is there anyway to write pairs of values to two columns, my text file currently contains data as such:

1 2 3 4 5 6 7 8

So I need to write the export as such:

A B
1 2
3 4
5 6
7 8

I know how to do this with a list specified in the code, but my text file is an output of earlier function and contains thousands of values I need to separate into two associated columns.

Currently I am stuck at

text = r"D:\Python\centers.txt"
csv = r"D:\Python\centers.csv"

    with open(text) as text_file:
        csv.reader(open(text, "rb"), delimiter = ' ')
        for row in text_file:
            out_csv = csv.reader(open(csv, 'wb'))
            out_csv.writerows(text)

Would specifying the text file as a list be a better option for this? Any help will be appreciated.

Here's my approach:

text = r"D:\Python\centers.txt"
csv = open(r"D:\Python\centers.csv", "w")

with open(text, 'r') as content_file:
    content = content_file.read()

content = content.split(" ")

print("A B", file=csv)

for i in range(0, len(content), 2):
    if (i+1 != len(content)):
        print("%s %s"%(content[i], content[i+1]), file=csv)


csv.close()

I read the whole text file in, and split it at ' ' , this gives me each number separately. Then I write AB to the csv file, by calling the print function and giving it the file to write to. Afterwards, I'm looping trough the numbers, but skipping every second index. If I'm not at the last number, I'm printing both numbers to the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM