Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
write to csv file problem
#5
(Nov-03-2023, 03:55 PM)jacksfrustration Wrote: i have the following function:

my_list=save_ent()
    new_list=[]

    for ent in my_list:
        new_list.append(output_found_flights(ent))
    try:
        data_file=pd.read_csv("flight_data.csv")
        data_dict=data_file.to_dict(orient="records")
    except pandas.errors.EmptyDataError:
        messagebox.showerror(title="Oooops",message="There are no saved information")
        data_dict=[]
    finally:
        for ent in new_list:
            data_dict.append(ent)
        try:
            for i,ent in enumerate(data_dict):
                res= not all (ent.values())
                if str(res):
                    data_dict.pop(i)
        except AttributeError:
            data_dict.pop(i)

        finally:

            new_data_file=pd.DataFrame(data_dict)
            new_data_file.to_csv("flight_data.csv",index=False)
the problem is the first time i run the code it executes correctly. When i try to add more search results it overwrites the csv file as expected but it gets rid of the previous search result and replaces it with the following


Output:
0 ""
ok i tried changing the mode as you suggested. i have the following code now

    my_list=save_ent()
    new_list=[]

    for ent in my_list:
        
        new_list.append(output_found_flights(ent))
    new_data_file=pd.DataFrame(new_list)
    new_data_file.to_csv("flight_data.csv",index=False,mode="a")
but i still get the following addition on my csv file


Output:
0 ""
in my code i have the output_found_flights function being called. the code for that follows


def output_found_flights(ent):
    '''connects to the api in order to find flights. information from entries are received
    generates values in the current entry that is supplied when the function is called
    and returns the updated dictionary file'''
    query = {
        "fly_from": ent['from_iata_code'],
        "fly_to": ent['to_iata_code'],
        "date_from": ent['from_time'],
        "date_to": ent["to_time"],
        "nights_in_dst_from": 7,
        "nights_in_dst_to": 28,
        "flight_type": "round",
        "one_for_city": 1,
        "max_stopovers": 0,
        "curr": "GBP"
    }
    headers = {
        "apikey": API_KEY
    }
    endpoint = "https://api.tequila.kiwi.com/v2/search"
    response = requests.get(url=endpoint, headers=headers, params=query)
    flights = response.json()
    try:
        lowest_price = round(float(ent["lowest_price"]), 2)
    except ValueError:
        messagebox.showerror(title="Ooops",
                             message="You have not entered appropriate input for the lowest price variable")

    for i in range(0, len(flights['data'])):
        flight_price = round(float(flights['data'][0]['price']), 2)
        if flight_price <= lowest_price:
            adult_price=flights['data'][i]['fare']['adults']
            children_price=flights['data'][i]['fare']['children']
            infants_price=flights['data'][i]['fare']['infants']
            total_price=float((adult_price * ent['adults'] ) + (children_price * ent['children']) + (infants_price * ent['infants']))
            url = flights['data'][i]['deep_link']
            date = flights['data'][i]['local_departure']
            date_separator = date.find("T")
            departure_date = date[:date_separator]
            date_list = departure_date.split("-")
            date_formatted = f"{date_list[2]}/{date_list[1]}/{date_list[0]}"
            ent['trip_date'] = date_formatted
            ent["ticket_price"] = flight_price
            ent['total_price']=total_price
            ent['url'] = url
            try:
                if messagebox.askokcancel(title=f"{ent['trip_date']} from {ent['from_city_name']} to {ent['to_city_name']}",message=f"Ticket price is £{ent['total_price']}0\n"
                                                                                                                                       f"{int(ent['adults'])} adults are travelling with {int(ent['children'])} children and {int(ent['infants'])} infants.\nPress ok to open the URL in order to buy the tickets"):
                    webbrowser.open(ent['url'])
            except ValueError:
                messagebox.showerror(title="Ooops",message="No flights were found")


            return ent
ent from the output_found_flights gets returned as empty the way i understand it. that is why i included the function code so you can help me figure out how to beat this
Reply


Messages In This Thread
write to csv file problem - by jacksfrustration - Nov-03-2023, 03:55 PM
RE: write to csv file problem - by noisefloor - Nov-03-2023, 05:05 PM
RE: write to csv file problem - by deanhystad - Nov-03-2023, 05:54 PM
RE: write to csv file problem - by deanhystad - Nov-03-2023, 10:22 PM
RE: write to csv file problem - by jacksfrustration - Nov-03-2023, 10:47 PM
RE: write to csv file problem - by deanhystad - Nov-04-2023, 05:43 AM
RE: write to csv file problem - by jacksfrustration - Nov-07-2023, 02:31 PM
RE: write to csv file problem - by deanhystad - Nov-07-2023, 03:55 PM
RE: write to csv file problem - by jacksfrustration - Nov-07-2023, 04:32 PM
RE: write to csv file problem - by deanhystad - Nov-07-2023, 06:30 PM
RE: write to csv file problem - by jacksfrustration - Nov-07-2023, 08:58 PM
RE: write to csv file problem - by deanhystad - Nov-09-2023, 01:56 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  What does .flush do? How can I change this to write to the file? Pedroski55 3 331 Apr-22-2024, 01:15 PM
Last Post: snippsat
  Last record in file doesn't write to newline gonksoup 3 512 Jan-22-2024, 12:56 PM
Last Post: deanhystad
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,633 Nov-09-2023, 10:56 AM
Last Post: mg24
  How do I read and write a binary file in Python? blackears 6 7,378 Jun-06-2023, 06:37 PM
Last Post: rajeshgk
  Reading data from excel file –> process it >>then write to another excel output file Jennifer_Jone 0 1,168 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
  Read text file, modify it then write back Pavel_47 5 1,728 Feb-18-2023, 02:49 PM
Last Post: deanhystad
  how to read txt file, and write into excel with multiply sheet jacklee26 14 10,506 Jan-21-2023, 06:57 AM
Last Post: jacklee26
  How to write in text file - indented block Joni_Engr 4 6,583 Jul-18-2022, 09:09 AM
Last Post: Hathemand
  Upgrading from 2 to 3 and having file write problems KenHorse 2 1,547 May-08-2022, 09:47 PM
Last Post: KenHorse
  Cursor write 3rd file empty paulo79 3 1,939 Mar-10-2022, 02:51 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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