Python 在文本平铺中的列之间插入逗号

Python 在文本平铺中的列之间插入逗号,python,Python,问题是我有一个缺少逗号的文本csv文件,我想插入它以便在LaTex上运行该文件并生成一个表。我有一个MWE的代码从另一个问题,我运行,它没有工作。有没有可能有人能指导我如何改变它 我使用了一个Python代码,它提供了一个空白文件,另一个提供了一个空白文档,还有一个删除了空格 import fileinput input_file = 'C:/Users/Light_Wisdom/Documents/Python Notes/test.txt' output= open('out.txt'

问题是我有一个缺少逗号的文本csv文件,我想插入它以便在LaTex上运行该文件并生成一个表。我有一个MWE的代码从另一个问题,我运行,它没有工作。有没有可能有人能指导我如何改变它

我使用了一个Python代码,它提供了一个空白文件,另一个提供了一个空白文档,还有一个删除了空格

 import fileinput
 input_file = 'C:/Users/Light_Wisdom/Documents/Python Notes/test.txt'
 output= open('out.txt','w+')
 with open('out.txt', 'w+') as output:
     for each_line in fileinput.input(input_file):
    output.write("\n".join(x.strip() for x in each_line.split(',')))
文本文件包含更多的数字,但如下所示

0   2.58612
0.00616025  2.20018
0.0123205   1.56186
0.0184807   0.371172
0.024641    0.327379
0.0308012   0.368863
0.0369615   0.322228
0.0431217   0.171899
Outcome
0.049282,   -0.0635003
0.0554422,  -0.110747
0.0616025,  0.0701394
0.0677627,  0.202381
0.073923,   0.241264
0.0800832,  0.193697
重新尝试:

with open("CSV.txt","r") as file:
    new = list(map(lambda x: ''.join(x.split()[0:1]+[","]+x.split()[0:2]),file.readlines()))
with open("New_CSV.txt","w+") as output:
    for i in new:
        output.writelines(i)
        output.writelines("\n")


这可以使用
.split
.join
将行拆分为一个列表,然后加入以逗号分隔的列表。这使我们能够处理文件中的几个后续空格:

f1 = open(input_file, "r")

with open("out.txt", 'w') as f2:
    for line in f1:
        f2.write(",".join(line.split()) + "\n")

f1.close()
您还可以使用
csv
自动处理写入:

import csv

f1 = open(input_file, "r")

with open("out.txt", 'w') as f2:
    writer = csv.writer(f2)
    for line in f1:
        writer.writerow(line.split())

f1.close()

你需要看文本文件吗?那会很有帮助的。整个文件不是必需的,但是布局是必需的helpful@DSC看起来我可以手动做标题,因为它被插入到乳胶中,它的数字让我很烦。你能给出预期的结果吗?您只需要在一行中的数字之间或不同行之间放置逗号吗?@DSC我在代码块中添加了结果