Search code examples
pythonloadsavequotesfile-format

Get rid of automatic quotes CSV file


I've made a dictionary with a tuple as key. The dictionary should look like this after i load it:

dictionary = {("key1", "key2"): "value"}

The problem is that when i save it into an CSV file it adds unnecessary quotes so it looks like this:

dictionary = {"("key1", "key2")": "value"}

My code that saves and loads the file looks like this:

def Save(self):
    w=csv.writer(open("file.csv", "w"))
    for key, val in self.dictionary.items():
        w.writerow([key, val])
def Load(self):
    self.dictionary={}
    for key, val in csv.reader(open("file.csv")):
        self.dictionary[key] = val
        print self.dictionary.keys()

Anyone knows how to do this? Thanks in advance.


Solution

  • I guessed what kind of class might have those methods, and produced this output in file.csv:

    "('key1', 'key2')",value
    

    This looks fine to me.

    Remember that the comma in your tuple has a different meaning in a CSV file: it is the field separator. csv.writer had to escape or quote that comma or the CSV file would have contained three columns instead of the two you were expecting. The typical escaping method is to wrap the cell's contents in quotation marks.

    Finally, CSV files never store objects, they store strings (technically bytes, which open converts to strings). Iterating over csv.reader returns a tuple of strings for each row in the CSV file, not of tuples or lists, or even integers.

    To convert that string back into some other data type, you'll have to either pass it to a function like int or float (if you happen to know it should be an integer or floating-point number), or evaluate the string. This a very dangerous thing to do, so don't try to evaluate the string yourself, and don't trust the built-in eval function to do it for you. Use the ast.literal_eval function, which exists to do this as safely as possible.