Table of Contents

Python Text File Reading

Example Description
Discover the art of reading and displaying data from text files in Python. Explore an in-depth tutorial on file reading, covering opening files, reading lines, and user interaction. Learn to efficiently access and present file data through practical examples.

Introduction:

Effectively reading and displaying data from text files is a vital skill for any Python developer. In this tutorial, we delve into file reading techniques, guiding you through opening files, reading lines, and user interactions. Through a step-by-step example, you’ll grasp how to access and present file data in an organized manner.

Code:

# program to create a text file and add data
fileobject=open("practice.txt","w+")
while True:
 data= input("Enter data to save in the text file: ")
 fileobject.write(data)
 ans=input("Do you wish to enter more data?(y/n): ")
 if ans=='n': break
fileobject=open("practice.txt","r")
str = fileobject.readline()
while str: 
 print(str)
 str=fileobject.readline()
fileobject.close() 

Logic:

  1. Create a file named “practice.txt” in write mode (“w+”) and assign the file object to fileobject.
  2. Use a while loop to repeatedly
  3. Prompt the user to input data they want to save in the text file using the input() function, and store the input in the variable data.
  4. Write the data to the file using the write method of fileobject.
  5. Ask the user whether they want to enter more data using the input() function and store the answer in the variable ans.
  6. If the user’s input is ‘n’, exit the loop using the break statement.
  7. Close the file using the close() method to save changes and release resources.
  8. Open the file “practice.txt” in read mode (“r”) and assign the file object to fileobject
  9. Use a while loop to read lines from the file using the readline() method.
  10. Initialize the variable str with the content of the first line.
  11. While str has content (not an empty line), print the content of str.
  12. Read the next line using readline and assign it to str
  13. Close the file using the close() method.

Output:

         >>Enter data to save in the text file: i love

>>Do you wish to enter more data?(y/n): y

>>Enter data to save in the text file: python

>>Do you wish to enter more data?(y/n): n

>>i lovepython