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

Time:03-29

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?

CodePudding user response:

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]

CodePudding user response:

As far as I know, quotations are fine with csv format. But if you want to remove the quotes, you can try the following. While importing the csv file, define the quotechar:

csv.reader(inp_file, delimiter=',', quotechar="'")
  • Related