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.
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()
- Open a file named “testfile.txt” in write mode (“w”) and assign the file object to fobject.
- 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.
- Write the content of the sentence variable to the file using the write() method of the fobject.
- Close the file using the close() method to save changes and release resources.
- Display “Now reading the contents of the file: ” to set the context for the output.
- Open the “testfile.txt” file in read mode (“r”) and assign the file object to fobject.
- 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.
- Close the file using the close() method.
>>Enter the contents to be written in the file: happy
>>Now reading the contents of the file: