I have a process where a CSV file can be downloaded, edited then uploaded again. On the download, the CSV file is in the correct format, with no wrapping double quotes
1, someval, someval2
When I open the CSV in a spreadsheet, edit and save, it adds double quotes around the strings
1, "someEditVal", "someval2"
I figured this was just the action of the spreadsheet (in this case, openoffice). I want my upload script to remove the wrapping double quotes. I cannot remove all quotes, just incase the body contains them, and I also dont want to just check first and last characters for double quotes.
Im almost sure that the CSV library in python would know how to handle this, but not sure how to use it...
EDIT When I use the values within a dictionary, they turn out as follows
{'header':'"value"'}
Thanks
Using the lstrip() function to remove double quotes from string in Python. The lstrip() function can remove characters from the start of the string. With this function, we can remove the double quotes from the start of the string.
Click on Replace (or hit CTRL + h). In the “Find what” field of the Dialog box type in a double quote. In the “Replace with” do nothing (or if you want some other character, put it here. Then either click the “Replace All” button to do everything at once, or click the “Replace” and go through one by one.
QUOTE_NONE ), the csv module uses the quotechar (which defaults to " ) to quote field. The following listing changes the quote character from double quote ( " ) to a single quote ( ' ). In this case, the csv module uses the single quote ( ' ) instead of ( " ) to quote fields containing quotechar or delimiter.
For you example, the following works:
import csv
writer = csv.writer(open("out.csv", "wb"), quoting=csv.QUOTE_NONE)
reader = csv.reader(open("in.csv", "rb"), skipinitialspace=True)
writer.writerows(reader)
You might need to play with the dialect options of the CSV reader and writer -- see the documentation of the csv
module.
Thanks to everyone who was trying to help me, but I figured it out. When specifying the reader, you can define the quotechar
csv.reader(upload_file, delimiter=',', quotechar='"')
This handles the wrapping quotes of strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With