Search code examples
pythonpython-3.xfileindexingindex-error

IndexError: list index out of range - PythonError


I'm creating a program that should create a file (.txt) based on each line of 'clouds.txt'. This is my code:

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()

The clouds.txt file looks like this:

>|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 >

Everything works fine until 'Mega48'. There I get "IndexError: list index out of range"

>|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|  >

I checked and there are no spaces/other characters. As you could see, after creating the file, the program deletes the line. After the error, if I'm starting the program again (and starts from 'Mega47') it doesn't show the error, and everything works as planned.

Any ideas how to fix this?


Solution

  • I see many mistakes in your code. First, what do you want with this list_lines = sum(1 for line in open('clouds.txt'))? You have a problem in your for loop because you did lines = f.readline() so lines is the first line, then you do for line in lines where line will be each character of the first line and there are more character in the first line than lines in your file to read.

    [edited]

    you don't need to know the number of lines in the file to do a for loop. You can just do for line in f:, then you don't need to read the line again with readline it is already in the variable line