Python code isnt printing contents of txt?

General Tech Bugs & Fixes 3 years ago

1.93K 3 0 0 0

User submissions are the sole responsibility of contributors, with TuteeHUB disclaiming liability for accuracy, copyrights, or consequences of use; content is for informational purposes only and not professional advice.

Answers (3)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 3 years ago
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?
0 views
0 shares

profilepic.png
manpreet 3 years ago

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

with ref="https://forum.tuteehub.com/tag/open">open("Hotel.txt", "r") as file:

0 views   0 shares

profilepic.png
manpreet 3 years 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: ")

0 views   0 shares

No matter what stage you're at in your education or career, TuteeHUB will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

Similar Forum