FILE HANDLING IN PYTHON PROGRAMMING
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:
It shows output as below:
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())
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
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.
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.
Well that's all the basic stuffs for file handling in python.