Reputation: 173
I have a list for example
['1 sam 2000','2 jack 1232','3 lily 34']
Each element in the list actually contains information for 3 columns and separated by spaces.
These were read from a txt
file.
Now I wish to save these data into a csv
file.
I read them using
with open('test.txt','r',encoding='utf-8',errors='ignore') as file:
li = []
for i in file:
i =i.rstrip('\n')
li.append(i)
Or shall can I simply convert txt into csv ?
Upvotes: 1
Views: 1143
Reputation: 11
you could skip the list step an go from a txt file directly to csv if you want, this would do the job:
import csv
with open('yourtextfile.txt', 'r') as in_file:
stripped = (line.strip() for line in in_file)
lines = (line.split(",") for line in stripped if line)
with open('result.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('title', 'intro'))
writer.writerows(lines)
i used this answer as example: Convert txt to csv python script
Upvotes: 1
Reputation: 13
## assumed data to format in the list format
## split each element in the list and create another list of list item
data=['1 sam 2000','2 jack 1232','3 lily 34']
## to save the final result initialize the variable
final_data=[]
## go though each element in the list
for i in data:
# split each element with the space
subdata=i.split(" ")
## add the element to the final_data
final_data.append(subdata)
## import pandas and convert list into pandas dataframe
## convert pandas dataframe to csv using to_csv method in pandas
import pandas as pd
pd.DataFrame(final_data).to_csv("result.csv")
Upvotes: 1
Reputation: 77407
You are reading a space-separated CSV file (awkward wording, I know) into a list. Just use the csv
module.
import csv
with open('test.txt','r',encoding='utf-8',errors='ignore', newline='') as file:
li = list(csv.reader(file, sep=' '))
Upvotes: 1
Reputation: 434
For every element of the list, you could use a split(" ")
to create a separate list and feed into the csv library:
import csv
data= ['1 sam 2000','2 jack 1232','3 lily 34']
with open("csv_file.csv", "w", newline="") as file:
writer = csv.writer(file)
for element in data:
writer.writerow(element.split(" "))
This should create a file called csv_file.csv with:
1,sam,2000
2,jack,1232
3,lily,34
If you need to add the headers, you can do it adding this line before the for loop:
writer.writerow((header1, header2, header3...))
Upvotes: 1