Dylan
Dylan

Reputation: 3

Python code isnt printing contents of txt?

elif menuOption == "2":
    with open("Hotel.txt", "a+") as file:
           print (file.read())

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?

Upvotes: 0

Views: 70

Answers (2)

Rohit
Rohit

Reputation: 4178

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: ")

Upvotes: 2

Alderven
Alderven

Reputation: 8270

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

with open("Hotel.txt", "r") as file:

Upvotes: 5

Related Questions