简体   繁体   中英

Reading a txt file and adding fixed headers/columns to a new csv file

I have a text file that looks like this

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)

I want to read the txt file and create a csv file in this format with header and remove the brackets

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

Here's the code

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)

The output

 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)

I tried removing the bracket using

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

but no luck

This file is not well suited to be read by csv . Instead treat it as a regular text file.

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']

Then you can write the contents of this array as you wish. For example, if you wanted the format you showed above.

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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