'Python : unable to convert text to csv properly
Trying to convert a text file to csv but in the converted file I am getting square brackets at the start and end of each line and single quotes surrounding each character.
in the 1st step, I am trying to remove the single quotes, but this seems to be not working
the code is given below:
with open('New-file_0.csv','w') as p3:
with open ('New-file_1','r') as p2:
for line in p2:
if not line.isspace():
print(line.split(),file = p3)
with open ('final-file_1.csv','w') as p2:
with open('New-file_0.csv','r') as p3:
for line in p3:
line=line.replace("'","")
print(line.split(),file = p2)
Solution 1:[1]
You're implicitly converting the split array to a string when printing it, which isn't formatting it the way you want. Use join to convert the array back to a comma-separated string.
print(",".join(line.split()), file=p2)
Solution 2:[2]
There are several issues here:
Instead of printing to files, generally use
p3.write(myline)
.split()
generates lists, which you are currently giving to your print function, so they are written to your files. What you want to give them instead is a string, e.g.",".join(line.split())
Since in this case, you want to produce a .csv file, it would be better to circumvent all that and use the builtin csv module, which will take care of turning your list into a string:
import csv with open(output_file,'wb') as p3: # make sure to use 'wb' for binary writing, or you will get unwanted empty rows output_data = csv.writer(p3, delimiter=",") with open (input_file,'r') as p2: for line in p2: row = line.strip().split() if row: output_data.writerow(row)
(This module also allows reading of .csv files into a list of rows using csv.read()
).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Brett |
Solution 2 |