Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.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 读取txt文件并将固定标题/列添加到新csv文件_Python_Csv_Rows - Fatal编程技术网

Python 读取txt文件并将固定标题/列添加到新csv文件

Python 读取txt文件并将固定标题/列添加到新csv文件,python,csv,rows,Python,Csv,Rows,我有一个像这样的文本文件 1 (2.10, 3) (4, 5) (6, 7) (2, 2) 2 (2.10, 3) (4, 5) (6, 7) (2, 2) 3 (6, 7) (2, 2) (30.2, 342) (6, 7) 我想读取txt文件,并创建一个csv文件,该文件采用这种格式,带有标题并删除括号 a,b,c,d,e,f,g,h,i 1,2.10,3,4,5,6,7,2,2 2,2.10,3,4,5,6,7,2,2 3,6,7,2,2,30.2,342,6,7 这是密码 impor

我有一个像这样的文本文件

1
(2.10, 3)
(4, 5)
(6, 7)
(2, 2)
2
(2.10, 3)
(4, 5)
(6, 7)
(2, 2)
3
(6, 7)
(2, 2)
(30.2, 342)
(6, 7)
我想读取txt文件,并创建一个csv文件,该文件采用这种格式,带有标题并删除括号

a,b,c,d,e,f,g,h,i
1,2.10,3,4,5,6,7,2,2
2,2.10,3,4,5,6,7,2,2
3,6,7,2,2,30.2,342,6,7
这是密码

import csv
import re
with open('test.txt', 'r') as csvfile:
csvReader = csv.reader(csvfile)
data = re.findall(r"\S+", csvfile.read())
array = []
array.append(data)
print (array)

file2 = open("file.csv", 'w')
writer = csv.writer(file2)
writer.writerows(array)
输出

 1,"(2.10,",3),"(4,",5),"(6,",7),"(2,",2),2,"(2.10,",3),"(4,",5),"(6,",7),"(2,",2),3,"(6,",7),"(2,",2),"(30.2,",342),"(6,",7)
我试着用手指取下支架

    array.append(str(data).strip('()'))

但是运气不好

此文件不适合csv读取。而是将其视为常规文本文件

array = []

with open('test.txt', 'r') as file_contents:
    for line in file_contents:
        # remove newlines, (), split on comma
        lsplit = line.strip().strip('()').split(',')
        # strip again to remove leading/trailing whitespace
        array.extend(map(str.strip, lsplit))

print(array)
#['1', '2.10', '3', '4', '5', '6', '7', '2', '2', '2', '2.10',
# '3', '4', '5', '6', '7', '2', '2', '3', '6', '7', '2', '2',
# '30.2', '342', '6', '7']
然后,您可以根据需要写入此数组的内容。例如,如果您想要上面显示的格式

header = ['a','b','c','d','e','f','g','h','i']
with open('file.csv', 'w') as file_out:
    file_out.write(",".join(header) + "\n")  # write the header
    for i in range(len(array)//len(header)):
        file_out.write(",".join(array[i*len(header):(i+1)*len(header)]) + "\n")

1、2、3等的间距是否始终一致?为什么要尝试以.csv文件的形式打开并读取.txt文件?如果您将其视为一个普通文本文件,然后逐行读取,创建要在csv中写入的数组,则会更好。可能会重复@chrisz是的,间距是一致的。我将+\n添加到行文件\u out.write、.joinheader中,它会以我想要的方式完美打印出来。非常感谢你。