Reputation: 667
I have the following in a .txt file
1.['LG','Samsung','Asus','HP','Apple','HTC']
2.['covid','vaccine','infection','cure','chloroquine']
3.['p2p','crypto','bitcoin','litecoin','blockchain']
How do I convert the above into a csv file under different columns?
My current code is this
import csv
with open('Full_txt_results.txt', 'r') as in_file:
stripped = (line.strip() for line in in_file)
lines = (line.split(",") for line in stripped if line)
with open('textlabels.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerows(lines)
the code currently gives the result in the following format in csv
Column 1 Column2 column 3 column 4 Column 5 column 6
['LG' 'Samsung' 'Asus' 'HP' 'Apple' 'HTC']
['covid' 'vaccine' 'infection' 'cure' 'chloroquine']
['p2p' 'crypto' 'bitcoin' 'litecoin' 'blockchain']
The texts are spilled in to different columns.
Ideal output required is in the below format
Column 1 Column2 column 3
LG Covid p2p
Samsung Vaccine crypto
Asus Infection bitcoin
HP cure litecoin
Apple chloroquine blockchain
HTC
Upvotes: 0
Views: 63
Reputation: 82785
Use ast
module to convert string to list object and then write to csv using writerow
method
Ex:
import csv
import ast
with open('Full_txt_results.txt') as in_file, open('textlabels.csv', 'w', newline="") as out_file:
writer = csv.writer(out_file)
data = [ast.literal_eval(line.strip().split(".")[1]) for line in in_file] #If you do not have column number(1.,2.,...) Use [ast.literal_eval(line.strip()) for line in in_file]
for row in zip(*data):
writer.writerow(row)
Demo:
import csv
import ast
with open(filename) as in_file, open(outfile, 'w', newline="") as out_file:
writer = csv.writer(out_file)
data = [ast.literal_eval(line.strip()) for line in in_file]
for row in zip(*data):
writer.writerow(row)
SRC txt file
['LG','Samsung','Asus','HP','Apple','HTC']
['covid','vaccine','infection','cure','chloroquine']
['p2p','crypto','bitcoin','litecoin','blockchain']
Output:
LG,covid,p2p
Samsung,vaccine,crypto
Asus,infection,bitcoin
HP,cure,litecoin
Apple,chloroquine,blockchain
Upvotes: 1