FILE HANDLING IN PYTHON PROGRAMMING

in #zzanlast month

To know the basic concept of the file handling in python programming, I have created a text file called "name.txt" which is as follows:


Screenshot_1.png

f=open('name.txt','r')
print(f.read())

It shows output as below:


Screenshot_2.png

If you want to print line by line then you use readline() inbuilt function in python.

f=open('name.txt','r')
print(f.readline())
print(f.readline())


Screenshot_3.png

If you mention something like f.readline(4) and then print it then only 4 characters of the first line will be printed which in this case the output is Umes.

This is all about handling the file in read mode (r) i.e. no new data is added or deleted which is already present. Let's see some example of opening the file in write mode(w).

f1=open('NewName.txt','w')
f1.write("New Name added is Pisoni")

You can see that a new text file has been created in the homepage of my Jupyter Notebook. When you click this file you can see what you have written in the above code. For now it's size is 0 B because nothing had been added but when you write something, it will take some space.


Screenshot_4.png


Screenshot_1.png

The problem with this one is that when you try to write a new data to your file the previous written data would be lost unless you want to write again and again with the same f1.write() statement. In such case we can append the data to the existing file.

f=open('name.txt','r')
f1=open('NewName.txt','w')
for data in f:
    f1.write(data)

When you run this code and checked for the NewName.txt file then you can see the following.

Screenshot_2.png

Well that's all the basic stuffs for file handling in python.

Sort:  

As a follower of @followforupvotes this post has been randomly selected and upvoted! Enjoy your upvote and have a great day!

Coin Marketplace

STEEM 0.16
TRX 0.03
JST 0.026
BTC 13704.83
ETH 405.53
USDT 1.00
SBD 0.99