Python CSV:无法上传文件。索引错误(“字符串索引超出范围”)

2024-04-27 03:06:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用Python导入一个文件:我理解为什么我有这个错误,但没有设法纠正它。代码尝试访问空行并返回超出范围的错误消息。我怎么才能改正呢?

file_data = csv_file.read().decode("utf-8")     
print("1")
lines = file_data.split("\n")
#loop over the lines and save them in db. If error , store as string and then display
for line in lines:
    if not line:
        continue
    line = line.strip()     
    print(line)      
    # following line may not be used, as line is a String, just access as an array
    #b = line.split()
    print(line[0]) 
    print("2")
    fields = line.split(",")
    data_dict = {}
    data_dict["project_name"] = fields[0]

 


Tags: and文件infieldsdataas错误line
1条回答
网友
1楼 · 发布于 2024-04-27 03:06:25

检查行是否为空

if not line:
    continue

line = line.strip()

但是当您删除它时,行可能变成空的,您不会检查它。

修正这些行的顺序,这样就得到:

line = line.strip()

if not line:
   continue


 

相关问题 更多 >