Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
write to csv file problem
#11
(Nov-07-2023, 06:30 PM)deanhystad Wrote: If there is nothing to write it doesn't matter how you try to write it. Fix the problem of there being nothing to write. Start by fixing saveEnt(). Should it ever return None?

i wrote the save_ent to check each entry if there is text there and if everything is completed it should output a dictionary.. here is my code


def save_ent():
    '''loops through up to the range of the count variable.
    for each iteration the name of the entry widgets is generated
    and the information is added into a list of dictionaries by
    appending each dictionary to the list.
    finally it returns the list of dictiionaries.
    Try/except/else and if statements used to cover all scenarios when reaceiving the data.
    for instance some of the entries should be in a numerical format.
    title method is also used to write the city names in uniform format'''
    saved_info=[]
    if from_city_ent.get():
        if to_city_ent.get():
            from_city_name = from_city_ent.get().title()
            to_city_name = to_city_ent.get().title()

            if check_iata_code():
                from_iata_code = from_iata_code_ent.get().upper()
                to_iata_code=to_iata_code_ent.get().upper()
            else:
                from_iata_code=get_iata_code(from_city_name)
                from_iata_code_ent.delete(0,END)

                from_iata_code_ent.insert(0,from_iata_code)

                to_iata_code = get_iata_code(to_city_name)

                to_iata_code_ent.delete(0,END)

                to_iata_code_ent.insert(0,to_iata_code)
                from_iata_code_ent.delete(0, END)
                to_iata_code_ent.delete(0, END)
                from_iata_code_ent.insert(0,from_iata_code)
                to_iata_code_ent.insert(0,to_iata_code)

            try:
                lowest_price = float(lowest_price_ent.get())

            except ValueError:
                messagebox.showerror(title="Ooops", message="There is no number in the highest price entry!!")

            else:
                try:
                    adult_tickets = int(amount_adult_ent.get())
                except ValueError:
                    messagebox.showerror(title="Ooops", message="There is no number in the adults entry!!")

                else:
                    try:
                        children_tickets = int(amount_children_ent.get())
                    except ValueError:
                        messagebox.showerror(title="Ooops", message="There is no number in the children entry!!")
                    else:
                        try:
                            infants_tickets = int(amount_infants_ent.get())
                        except ValueError:
                            messagebox.showerror(title="Ooops", message="There is no number in the infants entry!!")
                        else:
                            from_time = dt.datetime.now() + dt.timedelta(days=1)
                            to_time = dt.datetime.now() + dt.timedelta(days=(6 * 30))
                        finally:
                            saved_info.append({"from_city_name": from_city_name, "from_iata_code": from_iata_code,"to_city_name": to_city_name, "to_iata_code": to_iata_code, "lowest_price": lowest_price,"from_time":from_time.strftime("%d/%m/%Y"),'to_time':to_time.strftime("%d/%m/%Y"),"adults":adult_tickets,"children":children_tickets,"infants":infants_tickets})

                            return saved_info
so as you can see if there are appropriate inputs on all of the entries then it outputs the list of dictionaries. It should never return None but if there is a widget empty it should cancel the output. The way im checking it now is i check if there is text in from and to citie widgets. If there are numbers in price, adults,children,infant tickets and if the city names match the corresponding iata codes. if they dont match then new iata codes are generated based on the from and to city data entered by the user. finally it appends to saved_info(list of dictionaries) all the useful data used. this gets used in the found flights function which creates a dataframe from the output of save_ent adding total price, trip date, url for booking the tickets. these values are used in the newly created dataframe to append it to the csv file. However all i get in the csv file as i said before is

Output:
0 ""
which is not an issue with save_ent function. i've tried printing new_list contents which should be the output of the save_ent function filtered through the found_flights function and i get a value of None. The problem has to lie somewhere between the two functions i just for the life of me cannot understand where it's going wrong as i get the pop up with the relevant information (the pop up that gets triggered from the output_found_flights function). this pop up contains the information that gets added to the list of dictionaries namely the url, trip date and total price of tickets. even though the values get reflected in the pop up the output of the functions is None which shouldnt happen. Please help this is confusing the shite out of me
Reply
#12
if, if and should. I can't imagine why that might not return something.

That is some ugly code. A lot of the ugly is from using Entry. Entry is a terrible choice for entering information. For entering an integer I would think about using a spinbox. For entering departure or destination I would look at using a checkbox or option menu

If you want to use Entry I suggest subclassing Entry to make an IntEntry and an ListEntry that force users to enter valid information. These would have validation built into the control, so you don't have to write extra code to validate each entry object's value. The beauty of writing an Entry sublcass that does the validation is you only feel the pain once, when you write the sublcass. Currently you are feeling the pain each time you use an Entry widget to enter a number.

After you get the entry part fixed, you should change how your code uses the information. Your code should not allow the user to check a flight if there are errors in any of the entries. If your form has a submit button, I would disable the button if the form is not valid. Another choice is the submit button first checks the form, and only executes the submit callback if all the entries are valid. The more you can separate the data entry part of the program from the doing work part of the program, the cleaner and more robust your code will be.
Reply


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 232 Apr-22-2024, 01:15 PM
Last Post: snippsat
  Last record in file doesn't write to newline gonksoup 3 448 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,475 Nov-09-2023, 10:56 AM
Last Post: mg24
  How do I read and write a binary file in Python? blackears 6 6,704 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,116 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
  Read text file, modify it then write back Pavel_47 5 1,636 Feb-18-2023, 02:49 PM
Last Post: deanhystad
  how to read txt file, and write into excel with multiply sheet jacklee26 14 10,052 Jan-21-2023, 06:57 AM
Last Post: jacklee26
  How to write in text file - indented block Joni_Engr 4 6,478 Jul-18-2022, 09:09 AM
Last Post: Hathemand
  Upgrading from 2 to 3 and having file write problems KenHorse 2 1,499 May-08-2022, 09:47 PM
Last Post: KenHorse
  Cursor write 3rd file empty paulo79 3 1,903 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