please wait

  • Harsh Vashishth Mar-08-2019 12:24:03 PM ( 2 months ago )
    elif menuOption == "2":
        with open("Hotel.txt", "a+") as file:
               print (

    Ive tried many different ways but my python file just refuses to print the txt contents. It is writing to the file but option 2 wont read it.

    if menuOption == "1": print("Please Type Your Guests Name.") data1 = (input() + "\n") for i in range (2,1000): file = open("hotel.txt", "a") file.write(data1) print("Please Write your Guests Room") data2 = (input("\n") + "\n") file.write(data2) data3 = random.randint(1, 999999) file.write(str (data3)) print("Guest Added - Enjoy Your Stay.") print("Guest Name is:", data1) print("Guest Room Number Is:", data2) print("Your Key Code Is:", data3)

    I want all the above information to be added to a TXT. (That works) and then be able to read it also. which won't work. Why and how can I fix?
  • Jadav Payeng Mar-08-2019 12:25:42 PM ( 2 months ago )

    You have to use r instead of a+ to read from file:

    with open("Hotel.txt", "r") as file:
  • Priyanka Chadda Mar-08-2019 12:27:30 PM ( 2 months ago )

    You are using a+ mode which is meant for appending to the file, you need to use r for reading.

    Secondly I notice this

     for i in range (2,1000):
       file = open("hotel.txt", "a")

    You are opening a new file handler for every iteration of the loop. Please open the file just once and then do whatever operations you need to like below.

    with open("hotel.txt", "a") as fh:
        do your processing here...

    This has the added advantage automatically closing the file handler for you, otherwise you need to close the file handler yourself by using fh.close() which you are not doing in your code.

    Also a slight variation to how you are using input, you don't need to print the message explicitly, you can do this with input like this.

    name = input("Enter your name: ")

Please login

Similar Discussion

Recommended For You