Reputation: 91
I have the below python code which goes through my csv file, removes all percentage signs (%), and rewrites the file back into a new csv file.
Before I run my code, the data looks as such:
| Column 1 | Column 2 | Column 3 | Column 4 | etc |
Now, it looks like this:
| ['Column 1' | 'Column 2' | 'Column 3' | 'Column 4' | 'etc'] |
I don't want my data to include the brackets/apostrophes that are created by python's list functionality. I am afraid it will either, a) be included in my database when uploaded, or b) bomb out the import to the mySQL database. Any way around this?
Thanks in advance, Dan
Here is my code:
import csv
import string
input_file = open('Data.csv', 'r')
output_file = open('NewData.csv', 'w')
data = csv.reader(input_file)
writer = csv.writer(output_file)
specials = '%'
for line in data:
line = str(line)
new_line = str.replace(line,specials,'')
writer.writerow(new_line.split(','))
input_file.close()
output_file.close()
Upvotes: 2
Views: 2331
Reputation: 3131
The split(',')
method in Python will return a list. Join them together using whatever separator you desire. If new_line.split(',')
gives you something like ['Column1','Column2','Column3']
etc. then try
' | '.join(new_line.split(','))
This would give you something like Column1 | Column2 | Column3
.
The syntax is a little different than most ppl are used to from other languages, but the join method in Python must be called on the separator, with the target list passed as the parameter.
Upvotes: 2