目前,我使用csv
模块处理文件,该模块创建字典列表。
import csv
file = open('csvfile.csv')
lines = csv.reader(file)
header = next(lines) # ['name', 'price', 'date']
# when I do the following
for line in lines:
print(line)
# I get the following
['xxxx', '5.00', '2/23/2023']
# assigning types to the columns to do type conversion using a function
types = [
str,
float,
str # this need to be a tuple
# tried tuple(map(int, cannotchoosecolumn.split('/')))
# did not work
]
# now to create a list of dicts
alist_of_dicts = [
{
name: func(val)
for name, func, val in zip(header, types, line)
}
for line in lines
]
如何选择第三列str(2/23/2023)
以使用当前使用的格式更改为tuple(2, 21, 2007)
?
2条答案
按热度按时间7gs2gvoe1#
您可以向
types
列表传递一个函数:但是这段代码很难理解,我建议您使用
csv.DictReader
来读取csv,将其作为字符串字典-〉字符串,然后转换列zmeyuzjn2#
使用
csv.DictReader
并在读取列时对其进行转换:csvfile.csv
输出: