Python CSV将单个列作为列表读取

46qrfjad  于 2022-12-06  发布在  Python
关注(0)|答案(2)|浏览(135)

我有这样的代码:
type(i[0]) == 'str'。如何将其作为列表获取?然后获取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]))
w6lpcovy

w6lpcovy1#

它返回str而不是list的原因是csv编写器将始终执行与str(['a','b'])等效的操作,即"['a', 'b']",c,d,因此您可以使用ast.literal_eval字符串列表中获取列表,如下所示,对于第一个元素-

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])
lskq00tm

lskq00tm2#

你可以使用for循环,就像这样:
示例a.csv

hello, aloha, hola
bye, aloha, adios

Python代码:

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']

或者,您也可以使用列表解析:

import csv

col1 = []
with open('a.csv')  as file:
    r = csv.reader(file)
    col1 = [row[0] for row in r]

print(col1)  # => ['hello', 'bye']

相关问题