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

时间:2018-03-07 15:07:44

标签: 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

这是代码

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('()'))

但没有运气

1 个答案:

答案 0 :(得分:1)

此文件不适合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")