简体   繁体   English

Python写组到Coloumns

[英]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. 我设法创建了一个值文件的文本文件,需要将其写入csv或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 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. 然后,我通过调用print函数并将文件写入该文件,将AB写入该csv文件。 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. 如果我不是最后一个数字,则将两个数字都打印到文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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