I am handling a csv import and got troubles with a value that should be in list form but is read as string.
One of the csv rows looks like the following:
['name1', "['name2', 'name3']"]
As you can see the value in the second column is a list but is read as a string. My problem is that I need to iterate through that list and the length of that list can vary from row to row.
I am wondering where the problem lies. Can csv read not handle a list? Is there a way to turn that string in the second column into a list rather than using regex? Here is the code that I am running:
import csv
import os
content = []
file_path = os.path.abspath(file)
if os.path.exists(file_path):
with open(file_path, 'rb') as csvfile:
csvreader = csv.reader(csvfile, delimiter = ',')
for row in csvreader:
content.append(row)
for row in content[1:5]:
print row
print row[0], row[1]
for name in row[1]:
print name
The output row looks as above but when iterating though row[1] it does not iterate though the list of names but through every single character. Anyone got an idea? Thanks in advance for any help!
['name1', "['name2', 'name3']"].? How do you end up with nested lists?[date, text, id, 'name1', "['name2', 'name3']"]meaning that user1 mentions both user2 and user3. At time of creating csv it seemed like most convenient solution