IndexError:列表索引超出范围-PythonError

问题描述

我正在创建一个程序,该程序应基于“ clouds.txt”的每一行创建一个文件(.txt)。这是我的代码

def CreateFile():
    global file_name
    f = open(file_name,"w+")
    f.write(list_email + ":")
    f.close()

def WriteInConfig():
    f = open("config/config.txt","a")
    f.write(list_name + "\n")
    f.close()



with open("clouds.txt","r") as f:
    
    list_lines = sum(1 for line in open('clouds.txt'))
    
    lines = f.readline()
    for line in lines:
            
        first_line = f.readline().strip()
        list_email = first_line.split('|')[1] #email
        print("Email: " + list_email)

        list_pass = first_line.split('|')[2] #pass
        print("Pass: " + list_pass)
            
        list_name = first_line.split('|')[3] #name
        print(list_name)

        global file_name
        file_name = "config/." + list_name + ".txt"

        with open('clouds.txt','r') as fin:
            data = fin.read().splitlines(True)
        with open('clouds.txt','w') as fout:
            fout.writelines(data[1:])

        CreateFile()
        WriteInConfig()

clouds.txt文件如下:

>|clouds.n1c0+mega01@gmail.com|cwSHklDIybllCD1OD4M|Mega01|15|39.91|FdUkLiW0ThDeDkSlqRThMQ| |x
|clouds.n1c0+mega02@gmail.com|tNFVlux4ALC|Mega02|50|49.05|lq1cTyp13Bh9-hc6cZp1RQ|xxx|x
|clouds.n1c0+mega03@gmail.com|7fe4196A4CUT3V|Mega03|50|49.94|BzW7NOGmfhQ01cy9dAdlmg|xxx|xxx >

一切正常,直到“ Mega48”为止。出现“ IndexError:列表索引超出范围”

>|clouds.n1c0+mega47@gmail.com|bd61t9zxcuC1Yx|Mega47|50|10|Xjff6C8mzEqpa3VcaalUuA|xxx|x
|clouds.n1c0+mega48@gmail.com|kBdnyB6i0PUyUb|Mega48|50|0|R6YfuGP2hvE-uds0ylbQtQ|xxx|x
|clouds.n1c0+mega49@gmail.com|OcAdgpS4tmSLTO|Mega49|50|28.65|xxx|  >

我检查了,没有空格/其他字符。如您所见,创建文件后,程序将删除该行。错误发生后,如果我再次启动程序(并从“ Mega47”开始),则不会显示错误,并且一切都按计划进行。

有什么办法解决这个问题吗?

解决方法

我在您的代码中看到许多错误。首先,您要这个list_lines = sum(1 for line in open('clouds.txt'))使用什么? 您在for循环中遇到问题,因为您做了lines = f.readline(),所以行是第一行,然后执行for line in lines,其中line将是第一行的每个字符,而第一行中有更多字符比文件中的行要读取。

[已编辑]

您不需要知道文件中的行数即可进行for循环。您只需要执行for line in f:,就不需要使用readline再次读取该行,因为它已经在变量line