Python code isnt printing contents of txt?

General Tech Bugs & Fixes 2 years ago

0 3 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (3)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 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?
profilepic.png
manpreet 2 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 2 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.