Python Forum

Full Version: IndexError: list index out of range
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Hello guys...

What's going on with my code?
from tempfile import NamedTemporaryFile
from FlightRadar24.api import FlightRadar24API
from time import time, sleep
from datetime import datetime
import shutil
import csv
from pandas import DataFrame
import re
import threading
import schedule 
import time 
import sched, time

nav = []
n_acft_voando = []
while True:    

    fr_api = FlightRadar24API()
    empresas = ['AZU', 'GLO', 'LAN']
    #, 'JBU', 'AAL', 'DAL', 'ACA', 'UAL'
    pattern = "<(.*?)>"

    agora = datetime.now()
    dia = agora.strftime("%d/%m/%Y")
    hora = agora.strftime("%H:%M:%S")

    for i in range(0,len(empresas)):
        nav.append(len(fr_api.get_flights(airline = empresas[i])))
        dados_voo = fr_api.get_flights(airline = empresas[i])

        for k in range (0,len(dados_voo)):
            substring = re.search(pattern, str(dados_voo[k])).group(1)
            substring = substring.split(' - ')
            modelo_tail = [x.replace(" ", ";") for x in substring]
            n_acft_voando = [dia, hora, nav[0], nav[1], nav[2]]
            acft_voando=[dia, hora, modelo_tail[0]]
            print(acft_voando)

            with open(r'C:\Users\bruno\Desktop\Voos\DB\AeronavesAr.txt', 'a', newline='') as f:
                writer = csv.writer(f, delimiter=';')
                writer.writerow(n_acft_voando)

            with open(r'C:\Users\bruno\Desktop\Voos\DB\DetalhesAeronaves.txt', 'a', newline='') as f:
                writer = csv.writer(f, delimiter=';')
                writer.writerow(acft_voando)

    sleep(60)
I'm getting the following error:
Error:
IndexError Traceback (most recent call last) <ipython-input-2-aac74b35f2b2> in <module> 33 substring = substring.split(' - ') 34 modelo_tail = [x.replace(" ", ";") for x in substring] ---> 35 n_acft_voando = [dia, hora, nav[0], nav[1], nav[2]] 36 acft_voando=[dia, hora, modelo_tail[0]] 37 print(acft_voando) IndexError: list index out of range
How can I fix it?
It's interesting because, smetimes it works, and sometimes it doesn't.
list index out of range means you've used an index that is beyond the end of the list.

In your case you refer to nav[2] in that expression. If nav does not have three elements in it when that expression is evaluated, you'll get that error.

nav starts off empty and you only add one element to it when you reach line 28, so this should fail every time, unless dados_voo is empty. If that's empty, then you don't enter the loop and have a chance to make nav longer.
(Mar-25-2021, 04:51 AM)bowlofred Wrote: [ -> ]list index out of range means you've used an index that is beyond the end of the list.

In your case you refer to nav[2] in that expression. If nav does not have three elements in it when that expression is evaluated, you'll get that error.

nav starts off empty and you only add one element to it when you reach line 28, so this should fail every time, unless dados_voo is empty. If that's empty, then you don't enter the loop and have a chance to make nav longer.

Thank you...
But, how could you fix it?
I have no idea
Don't call this:
n_acft_voando = [dia, hora, nav[0], nav[1], nav[2]]
Until you've done this three times:
    for i in range(0,len(empresas)):
        nav.append(len(fr_api.get_flights(airline = empresas[i])))
It is difficult to say how such a thing is accomplished since it depends as much on what the program does as the nuts and bolts of coding the program so it doesn't crash. Right now all I have to work with is some code that doesn't work. it is difficult to know how to fix it unless I know what it is SUPPOSED to do.

What does this line do?
n_acft_voando = [dia, hora, nav[0], nav[1], nav[2]]
[/python]
Why does in need nav[0], nave[1] and nav[2]? What are nav[0], nav[1] and nav[2]?
I find it suspicious that these indices are hard coded when the outer loop may run more than 3 times based on this:
    empresas = ['AZU', 'GLO', 'LAN']
    #, 'JBU', 'AAL', 'DAL', 'ACA', 'UAL'
Is this a hint that empresas may be a larger list?. If so, maybe the proper way to code this is:
    for i in range(2):
        nav.append(len(fr_api.get_flights(airline = empresas[i])))

    for i in range(2,len(empresas)):
        nav.append(len(fr_api.get_flights(airline = empresas[i])))
        dados_voo = fr_api.get_flights(airline = empresas[i])
 
        for k in range (0,len(dados_voo)):
            substring = re.search(pattern, str(dados_voo[k])).group(1)
            substring = substring.split(' - ')
            modelo_tail = [x.replace(" ", ";") for x in substring]
            n_acft_voando = [dia, hora, nav[i-2], nav[i-1], nav[i]]
            acft_voando=[dia, hora, modelo_tail[0]]
            print(acft_voando)
 
            with open(r'C:\Users\bruno\Desktop\Voos\DB\AeronavesAr.txt', 'a', newline='') as f:
                writer = csv.writer(f, delimiter=';')
                writer.writerow(n_acft_voando)
 
            with open(r'C:\Users\bruno\Desktop\Voos\DB\DetalhesAeronaves.txt', 'a', newline='') as f:
                writer = csv.writer(f, delimiter=';')
                writer.writerow(acft_voando)
Again, I don't know if this is correct.
(Mar-25-2021, 01:42 PM)deanhystad Wrote: [ -> ]Don't call this:
n_acft_voando = [dia, hora, nav[0], nav[1], nav[2]]
Until you've done this three times:
    for i in range(0,len(empresas)):
        nav.append(len(fr_api.get_flights(airline = empresas[i])))
It is difficult to say how such a thing is accomplished since it depends as much on what the program does as the nuts and bolts of coding the program so it doesn't crash. Right now all I have to work with is some code that doesn't work. it is difficult to know how to fix it unless I know what it is SUPPOSED to do.

What does this line do?
n_acft_voando = [dia, hora, nav[0], nav[1], nav[2]]
[/python]
Why does in need nav[0], nave[1] and nav[2]? What are nav[0], nav[1] and nav[2]?
I find it suspicious that these indices are hard coded when the outer loop may run more than 3 times based on this:
    empresas = ['AZU', 'GLO', 'LAN']
    #, 'JBU', 'AAL', 'DAL', 'ACA', 'UAL'
Is this a hint that empresas may be a larger list?. If so, maybe the proper way to code this is:
    for i in range(2):
        nav.append(len(fr_api.get_flights(airline = empresas[i])))

    for i in range(2,len(empresas)):
        nav.append(len(fr_api.get_flights(airline = empresas[i])))
        dados_voo = fr_api.get_flights(airline = empresas[i])
 
        for k in range (0,len(dados_voo)):
            substring = re.search(pattern, str(dados_voo[k])).group(1)
            substring = substring.split(' - ')
            modelo_tail = [x.replace(" ", ";") for x in substring]
            n_acft_voando = [dia, hora, nav[i-2], nav[i-1], nav[i]]
            acft_voando=[dia, hora, modelo_tail[0]]
            print(acft_voando)
 
            with open(r'C:\Users\bruno\Desktop\Voos\DB\AeronavesAr.txt', 'a', newline='') as f:
                writer = csv.writer(f, delimiter=';')
                writer.writerow(n_acft_voando)
 
            with open(r'C:\Users\bruno\Desktop\Voos\DB\DetalhesAeronaves.txt', 'a', newline='') as f:
                writer = csv.writer(f, delimiter=';')
                writer.writerow(acft_voando)
Again, I don't know if this is correct.

Thank you so much!
I really appreciate your help

It's working better now...

Let me ask you another question:
Why am I getting the following output:
25/03/2021;10:00:40;"(B763);CC-CXK"
25/03/2021;10:00:40;"(B789);CC-BGN"
I want to get values without those quotes, like:
25/03/2021;10:00:40;(B763);CC-CXK
25/03/2021;10:00:40;(B789);CC-BGN
How can I get rid of these double quotes?
(Mar-25-2021, 02:04 PM)brunolelli Wrote: [ -> ]Why am I getting the following output:
Because you have a string that has inside the delimiter used in the file - ;. So, if it is not quoted (B763) will be one column and CC-CXK will be next column.

You can always set quoting to csv.QUOTE_NONE, but that's obviously not advisable.
(Mar-25-2021, 02:13 PM)buran Wrote: [ -> ]
(Mar-25-2021, 02:04 PM)brunolelli Wrote: [ -> ]Why am I getting the following output:
Because you have a string that has inside the delimiter used in the file - ;. So, if it is not quoted (B763) will be one column and CC-CXK will be next column.

You can always set quoting to csv.QUOTE_NONE, but that's obviously not advisable.

The fact is that I don't want this information as it's written... I really need it separated, (B738) in one collumn and PR-YSA in another column. How can I do that?
writer = csv.writer(f, delimiter=';', quoting = csv.QUOTE_NONE)
Note - I didn't look at previous discussion - maybe it's a problem that it was not split when the rest was split? I see the code is quite confusing and unclear and we don't have the source data.
(Mar-25-2021, 02:26 PM)buran Wrote: [ -> ]
writer = csv.writer(f, delimiter=';', quoting = csv.QUOTE_NONE)
Note - I didn't look at previous discussion - maybe it's a problem that it was not split when the rest was split? I see the code is quite confusing and unclear and we don't have the source data.

Yep, I totally agree with you..
This is my first time programming and I have no previus experience with Python...
I'll try to explain my problem and how I'm trying to solve it with this code:

Basically, running this code I'm able to collect some info of aircrafts flying right now from an airline called AZU
from FlightRadar24.api import FlightRadar24API
fr_api = FlightRadar24API()

fr_api.get_flights(airline = 'AZU')
And the output looks like this:
[<(A332) PR-AIW - Altitude: 25300 - Ground Speed: 429 - Heading: 328>,
 <(A20N) PR-YSC - Altitude: 27850 - Ground Speed: 436 - Heading: 216>,
 <(A20N) PR-YRV - Altitude: 12900 - Ground Speed: 370 - Heading: 251>,
 <(C208) PR-WOT - Altitude: 1900 - Ground Speed: 164 - Heading: 84>,
 <(E295) PS-AEH - Altitude: 28725 - Ground Speed: 432 - Heading: 44>,
 <(A20N) PR-YSF - Altitude: 6725 - Ground Speed: 282 - Heading: 32>,
 <(A20N) PR-YSG - Altitude: 20575 - Ground Speed: 424 - Heading: 209>,
 <(E195) PR-AXY - Altitude: 27000 - Ground Speed: 453 - Heading: 72>,
 <(E195) PR-AXB - Altitude: 17650 - Ground Speed: 345 - Heading: 210>]
But I would like to run this code for more than one airline, like 'AZU', 'GLO', 'AAL', 'UAL', and so on...
And export this data to a TXT file, adding more two columns ([Date][Time]).

Moreover, I would like to run this code every minute, and keep upadating my TXT file.
How can I do that?
Pages: 1 2