Table of Contents
Example Description
Discover how to effortlessly manage text files in Python. Learn the art of writing and reading data to and from files, streamlining your data storage and retrieval processes. Explore practical examples and boost your Python programming skills today.

Introduction:

Text file handling is a core skill for programmers managing data. In this tutorial, we dive into writing and reading data to and from text files. Through a step-by-step example, you’ll grasp how to create, write, and read text files using Python. Enhance your programming prowess with these essential techniques.

Code:

fobject=open("testfile.txt","w") # creating a data file
sentence=input("Enter the contents to be written in the file: ")
fobject.write(sentence) # Writing data to the file
fobject.close() # Closing a file
print("Now reading the contents of the file: ")
fobject=open("testfile.txt","r")
#looping over the file object to read the file
for str in fobject: 
  print(str)
fobject.close()

Logic:

  1. Open a file named “testfile.txt” in write mode (“w”) and assign the file object to fobject.
  2. Prompt the user to input a sentence to be written to the file using the input() function, and store the input in the variable sentences.
  3. Write the content of the sentence variable to the file using the write() method of the fobject.
  4. Close the file using the close() method to save changes and release resources.
  5. Display “Now reading the contents of the file: ” to set the context for the output.
  6. Open the “testfile.txt” file in read mode (“r”) and assign the file object to fobject.
  7. Loop over the lines of the file using a for loop and the file object fobject. For each line, print the content of the line.
  8. Close the file using the close() method.

Output:

>>Enter the contents to be written in the file: happy

>>Now reading the contents of the file:

>>happy