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:
- Create a file named “practice.txt” in write mode (“w+”) and assign the file object to fileobject.
- Use a while loop to repeatedly
- 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.
- Write the data to the file using the write method of fileobject.
- Ask the user whether they want to enter more data using the input() function and store the answer in the variable ans.
- If the user’s input is ‘n’, exit the loop using the break statement.
- Close the file using the close() method to save changes and release resources.
- Open the file “practice.txt” in read mode (“r”) and assign the file object to fileobject
- Use a while loop to read lines from the file using the readline() method.
- Initialize the variable str with the content of the first line.
- While str has content (not an empty line), print the content of str.
- Read the next line using readline and assign it to str
- 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