Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将文本文件转换为无索引的csv文件_Python_Pandas - Fatal编程技术网

Python 将文本文件转换为无索引的csv文件

Python 将文本文件转换为无索引的csv文件,python,pandas,Python,Pandas,我有一个包含数据的testx文件 1 1 1 1 1 2 3 4 4 4 4 要将其作为csv文件读取 data = pd.read_csv("file.txt",sep="\n",header=none) 但这是在增加 0, 1,1 1 1 1 1 2,2 3,3 4 4 4 4 我怎样才能删除索引而不是文件,这样我就可以得到一个csv文件 data = pd.read_csv("file.txt",sep="\n",header=none) 当然,我

我有一个包含数据的testx文件

1 1 1 1 1 
2
3 4 4 4 4
要将其作为csv文件读取

data = pd.read_csv("file.txt",sep="\n",header=none)
但这是在增加

   0,
    1,1 1 1 1 1 
    2,2
    3,3 4 4 4 4
我怎样才能删除索引而不是文件,这样我就可以得到一个csv文件

data = pd.read_csv("file.txt",sep="\n",header=none)
当然,我写的
index=false
逗号也不见了

我正在寻找输出

,1 1 1 1 1 
,2
,3 4 4 4 4
因为我的输入程序只接受csv文件,所以请尝试以下操作:

from io import StringIO

csvtext = StringIO("""1 1 1 1 1 
2
3 4 4 4 4""")

data = pd.read_csv(csvtext, sep='\n', header=None)

data.to_csv('out.csv', index=False, header=False)

#on windows

!type out.csv
输出:

1 1 1 1 1 
2
3 4 4 4 4

如果我理解你的意思,我想你只需要阅读而不需要修改,试试这个:

import csv

with open('file.txt', newline='') as txt_file:
    csv_file = csv.reader(txt_file, delimiter=' ')

    #if you need to convert it to csv file:
    with open ('file.csv', "w",newline='') as new_csv_file:
        new_csv = csv.writer(new_csv_file, delimiter=',')

        for row in csv_file:
            print(' '.join(row))
            new_csv.writerow(row)
以csv格式输出(您的预期输出是而不是):


我已经编辑了答案,因此如果您想编写csv文件,现在可以使用前面的代码。您可以使用csv模块解决格式问题。

发布最终预期结果我已经添加了我想要的预期结果。@MLlearner使用相同的代码,在记事本od记事本++中打开输出文件?每个数字后面都有逗号,我想用逗号分隔这个文件only@MLlearner您可以将分隔符更改为您喜欢的任何字符,甚至是空格