Python Forum
IndexError: list index out of range
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
IndexError: list index out of range
#11
First of all - sorry to tell you, but you are doing it wrong.
get_flight() returns a list of FlightRadar24.flight.Flight objects. Every object has methods and you can access them, no need for all this complication to convert to string and then parse it.

import csv
from datetime import datetime
from FlightRadar24.api import FlightRadar24API
fr_api = FlightRadar24API()
 
flights = fr_api.get_flights(airline = 'AZU')
print(type(flights[0]))
print(flights[0].__dict__)

with open('fr24.csv', 'w') as f:
    fieldnames = ['time', 'aircraft_code', 'registration', 'altitude', 'ground_speed', 'heading'] # you can include whatever attributes you want
    wrtr = csv.DictWriter(f, fieldnames=fieldnames, extrasaction='ignore')
    wrtr.writeheader()
    for flight in flights:
        flight.time = datetime.fromtimestamp(flight.time) # convert the timestamp to datetime object
        wrtr.writerow(flight.__dict__) # here I pass all attributes as dict, but you can always access individual attributes, like I did with time above
the output

Output:
<class 'FlightRadar24.flight.Flight'> {'id': '273002c6', 'icao_24bit': 'E495B3', 'latitude': -23.6238, 'longitude': -46.6602, 'heading': 236, 'altitude': 0, 'ground_speed': 4, 'squawk': '5107', 'aircraft_code': 'A20N', 'registration': 'PR-YSE', 'time': 1616685581, 'origin_aiport_iata': 'REC', 'destination_airport_iata': 'CGH', 'number': 'AD4251', 'airline_iata': 'AD', 'on_ground': 1, 'vertical_speed': 0, 'callsign': 'AZU4251', 'airline_icao': 'AZU'}
fr24.csv

Output:
time,aircraft_code,registration,altitude,ground_speed,heading 2021-03-25 17:19:41,A20N,PR-YSE,0,4,236 2021-03-25 17:19:42,A20N,PR-YSD,3500,141,73 2021-03-25 17:19:37,E195,PR-AUK,36000,448,336 2021-03-25 17:19:40,A20N,PR-YRN,0,12,132 2021-03-25 17:19:42,A20N,PR-YRD,37050,470,27 2021-03-25 17:19:41,A339,PR-ANX,40000,462,332 2021-03-25 17:19:41,AT76,PR-AQQ,16525,301,350 2021-03-25 17:19:42,A20N,PR-YYG,37825,459,359 2021-03-25 17:19:38,AT76,PR-AQJ,8075,197,350 2021-03-25 17:19:42,E195,PR-AYO,6875,198,60 2021-03-25 17:19:41,C208,PT-MED,4700,173,108 2021-03-25 17:19:42,AT76,PR-AQR,21025,267,92 2021-03-25 17:19:41,E295,PS-AEG,4625,172,73 2021-03-25 17:19:38,AT76,PR-AKB,10075,256,269 2021-03-25 17:19:42,E195,PR-AUJ,3350,153,128 2021-03-25 17:19:42,E295,PR-PJN,4525,193,71 2021-03-25 17:19:42,E195,PR-AUH,37000,474,8 2021-03-25 17:19:39,A20N,PR-YRE,0,19,309 2021-03-25 17:19:42,A20N,PR-YSG,38000,441,221 2021-03-25 17:19:41,A20N,PR-YRW,12000,259,307 2021-03-25 17:19:42,AT76,PR-AKF,16925,179,347 2021-03-25 17:19:41,A21N,PR-YJB,27800,478,313 2021-03-25 17:19:41,A20N,PR-YYJ,0,12,317
Now, I didn't look into details - e.g. iz it possible to retrieve info for multiple companies or you need to make separate requests, but you get the idea.
Also, if you are going to scrap large amount of information - maybe it's better to look at some database, e.g. sqlite3 support comes with python standard library. Also consider that API can blok you if you are heavy on them - check their allowed limits.

Finally - maybe you need to take some tutorial/course, incl. about objects, OOP, etc.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#12
(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.

YOU ARE THE BEST!
THANK YOU SO MUCH!!!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  IndexError: index 10 is out of bounds for axis 0 with size 10 Mehboob 11 1,947 Sep-14-2023, 06:54 AM
Last Post: Mehboob
Thumbs Down I hate "List index out of range" Melen 20 3,154 May-14-2023, 06:43 AM
Last Post: deanhystad
Exclamation IndexError: Replacement index 2 out of range for positional args tuple - help? MrKnd94 2 5,954 Oct-14-2022, 09:57 PM
Last Post: MrKnd94
  IndexError: list index out of range dolac 4 1,843 Jul-25-2022, 03:42 PM
Last Post: deanhystad
  I'm getting a String index out of range error debian77 7 2,269 Jun-26-2022, 09:50 AM
Last Post: deanhystad
  IndexError: list index out of range Anldra12 2 1,408 May-03-2022, 01:39 PM
Last Post: Anldra12
  TypeError: list indices must be integers or slices, not range Anldra12 2 2,499 Apr-22-2022, 10:56 AM
Last Post: Anldra12
  matplotlib x axis range goes over the set range Pedroski55 5 3,101 Nov-21-2021, 08:40 AM
Last Post: paul18fr
  IndexError: list index out of range rf_kartal 6 2,759 Sep-07-2021, 02:36 PM
Last Post: Larz60+
  Python Error List Index Out of Range abhi1vaishnav 3 2,233 Sep-03-2021, 08:40 PM
Last Post: abhi1vaishnav

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020