我有一个包含4列的csv文件,如下所示:
ID、制造商、型号、年份
33527,宝马,3系Gran Turismo,2018年
5335,福特,F-150,1990
458,丰田,凯美瑞,1994
14565,丰田,凯美瑞,1998年
..。
..。
..。
我想把这个csv转换成一个“不使用任何库或导入”的列表。
我希望结果是一个列表列表,并且只包含如下所示的第1、2和4列:
[33527,宝马,2018年,5335,福特,1990年,458,丰田,1994年,14565,丰田,1998年,....]
如果没有任何库的帮助,我应该如何制作这个列表?
谢谢你的帮助。
发布于 2020-08-17 06:08:28
使用基本构建块:打开文件,逐行读取(并忽略标题行),每行创建新的列表并将其添加到现有列表(追加)
items = list()
with open('temp.csv','r') as fp: # open the csv file for reading (will close when "with" block ends)
header_line = fp.readline() # keep headers for future use
for line in fp.readlines(): # go over remaining lines
col = line.strip().split(",") # get the columns of data
new_item = [col[0],col[1],col[3]] # keep only 1st, 2nd, 4th items in a new list, starting count from 0, since this is how lists work in python
items.append(new_item) # add the current item to the item list
print(items)
https://stackoverflow.com/questions/63441785
复制相似问题