python - 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))
解决方案
您的最后一条数据线以\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))
推荐阅读
- cmake - 使用 libwebsockets 启用 libuv 编译时出现问题
- jquery - 使用 AJAX 交换的按钮会导致新按钮的侦听器被忽略
- r - 在多变量关系中分配值
- ruby-on-rails - 为设计对象创建根和路由
- ios - iframe 可以在带有 Cordova 的 WKWebView 中工作吗?
- javascript - 如何在 Vue 中以 Typescript 语法定义使用 prop 作为其初始值的本地数据属性?
- ruby-on-rails - 我怎样才能对`counter_cache`提出一个独特的请求
- c# - C# Unity 错误:无法加载文件或程序集
- typescript - 我将如何解决“没有导出的成员”
- mongodb - 将快递容器连接到具有体积的 mongo 容器