Search code examples
pythonpython-3.xcsvexport-to-csvsingle-quotes

How to remove single quotes from imported csv file into a list?


I export a list into a csv file as:

file = open('all_states.csv', 'w+', newline='')

# writing the data into the file
with file:
    write = csv.writer(file)
    write.writerows(all_states)

And from another script I import the csv file as:

with open('all_states.csv') as file:

    reader = csv.reader(file)

    states = list(reader)

file.close()

The original data that was exported was:

exp_data = [
    [[0], [[1, 0, 0], [1, 0, 0], [0, 1, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 0], [0, 1, 0]], [0, 0, 1]], 
    [[0], [[1, 0, 0], [1, 0, 0], [0, 1, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 0], [0, 1, 0]], [-1, 0, 0]], 
    [[0], [[1, 0, 0], [1, 0, 0], [0, 1, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 0], [0, 1, 0]], [0, -1, 0]]
]

But when I imported I get some single quotes that I'd like to remove.

impo_data = [
    ['[0]', '[[1, 0, 0], [1, 0, 0], [0, 1, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 0], [0, 1, 0]]', '[0, 0, 1]'], 
    ['[0]', '[[1, 0, 0], [1, 0, 0], [0, 1, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 0], [0, 1, 0]]', '[-1, 0, 0]'], 
    ['[0]', '[[1, 0, 0], [1, 0, 0], [0, 1, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 0], [0, 1, 0]]', '[0, -1, 0]']
]

How can I remove the quotes when exporting or once imported?


Solution

  • The issue is that your CSV file is read as a string, while you want to process it as if it is not. Your items look like they are all JSON, so just run them through json.loads.

    states = [[json.loads(item) for item in row] for row in reader]