Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python CSV: Remove quotes from value

Tags:

python

csv

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

like image 409
neolaser Avatar asked Jan 20 '11 23:01

neolaser


People also ask

How do I remove a quote from a csv file in Python?

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.

How do I remove a quote from a CSV file?

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.

What does CSV Quote_none do?

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.


2 Answers

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.

like image 125
Sven Marnach Avatar answered Sep 30 '22 08:09

Sven Marnach


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.

like image 20
neolaser Avatar answered Sep 30 '22 07:09

neolaser