I have this code:
type(i[0]) == 'str'
. How can I get it as a list? and later get print(i[0][0]) == 'a'
import csv
i = [['a', 'b'], 'c', 'd']
with open('a.csv', 'a', newline='', encoding='utf-8') as file:
writer = csv.writer(file, delimiter=';')
writer.writerow(i)
file.close()
with open('a.csv', 'r', newline='', encoding='utf-8') as file:
for i in csv.reader(file, delimiter=';'):
print(type(i[0]))
CodePudding user response:
The reason it is returning str
instead of list
because the csv writer will always do the equivalent of str(['a','b'])
, which is "['a', 'b']",c,d
, so you can use ast.literal_eval
to get the list from the string list like this for the first element-
import csv
import ast
i = [['a', 'b'], 'c', 'd']
with open('a.csv', 'a', newline='', encoding='utf-8') as file:
writer = csv.writer(file, delimiter=';')
writer.writerow(i)
file.close()
with open('a.csv', 'r', newline='', encoding='utf-8') as file:
for i in csv.reader(file, delimiter=';'):
i[0] = ast.literal_eval(i[0])
print(type(i),type(i[0]), i[0][0])
CodePudding user response:
You can use a for-loop. Like this:
example a.csv
hello, aloha, hola
bye, aloha, adios
python code:
import csv
col1 = []
with open('a.csv') as file:
r = csv.reader(file)
for row in r:
col1.append(row[0])
print(col1) # => ['hello', 'bye']
Alternatively, you could also use a list comprehension:
import csv
col1 = []
with open('a.csv') as file:
r = csv.reader(file)
col1 = [row[0] for row in r]
print(col1) # => ['hello', 'bye']