Text File Handling in Python | Read and Write on Files with Python

Given a text file, with just a few lines of code, we can read the file and print all the text in the file. We can also write on it. Here is a simple code to read from a text file called 'Test.txt' and print all the text in the file, write something at in end of the file and read it again. This may seem tough but with all the features Python offers, it is actually quite simple.

Here is the file 'Test.txt':



and here is the code:

with open('Test.txt','r') as f:
    text = f.read()
    print(text)
    f.close()

with open('Test.txt','a') as f:
    write_text = input('\nEnter the text to write: ')
    f.write(write_text)
    f.close()

with open('Test.txt','r') as f:
    text = f.read()
    print(text)
    f.close()


The first block of code opens the file in a read format, takes all the text from the file, stores it in a string format in text, which we can use for anything, like printing. 

The second block takes an input from the user, again in string format and writes it onto the same file, now opened in append mode, which is just write mode without any data deletion. 

The third block is exactly the same as the first block, but the output now would contain the text entered in the second block also, showing us that the data entered in block #2 has been appended into the file. 

Let's look the the outputs:

Hello Fellow Pygrammers,

Do check out my other programs and be sure to spread the word.
I really hope these programs help you out.

If you have a suggestion for a program, leave it in the comments and I will check it out.

Enter the text to write: Do follow the blog if you like the posts.
Hello Fellow Pygrammers,

Do check out my other programs and be sure to spread the word.
I really hope these programs help you out.

If you have a suggestion for a program, leave it in the comments and I will check it out.Do follow the blog if you like the posts.
>>>


Clearly, the file contains some text which gets printed out in the first. Then we add some text to the end of the file and in the second file.read() execution, the new text also gets printed.

This kind of file reading and writing is very helpful to know and remember. There are some more functions with regard to file handling but let's keep that for later. Until then, do follow ThePygrammer to be updated everytime a new post comes out. Feel free to use the comment section below to share your queries if you have any. 

If you want to know how to prank your friend with a simple trick: Junk Text-Files Prank.

Comments