首页 > 解决方案 > I wanted to open a file with the module of python "open", and trying to make it in fragments, then, it appears this phrase "list index out of range"

问题描述

data2 = open("D:/python-ml-course-master/datasets/Netflix_movies/metadata.csv","r",encoding = "utf-8")

cols = data2.readline().strip().split(",")
n_cols = len(cols)

counter = 0

main_dict = {}
for col in cols:
    main_dict[col] = []

for line in cols:
    if counter > 0:
        values = line.strip().split(",")
        for i in range(len(cols)):
            main_dict[cols[i]].append(values[i])
    counter = counter + 1

print("El data set tiene %d filas y %d columnas"%(counter, n_cols))

标签: python

解决方案


您的最后一条数据线以\n. 之后拆分行的(空)内容时,您没有足够values的列。

使固定:

for line in cols:
    if counter > 0:
        values = line.strip().split(",")
        if len(values) == len(cols): 
            for (name,v) in zip(cols,values): 
                main_dict[name].append(v) 
                counter = counter + 1
        else:
            print(f"Not enough data in '{values}' to write a line")


print("El data set tiene %d filas y %d columnas"%(counter, n_cols))

推荐阅读