File Handling with Python || Python programming tutorial
Let us say we have a file name poem.txt and we need to perform various operations on that file.
Reading the whole file and printing it
- First, we need to open that text file in our python program using a function open().
- The open() function will take two arguments filename and set our intentions.
- Now, you must be wondering about the second argument i.e. we need to specify our purpose of using that file Read, Write and Append
- Above all operations can be specified by with different alphabets:
- Read - 'r'
- Write - 'w'
- Append - 'a'
Now we will implement programs with this knowledge
Program -
f = open("poem.txt", "r")
f.read()
Counting Number of Lines in our file
We will divide this process into various steps :
To read a single line of a file we can use readline method
Program -
f = open("poem.txt", "r")
number_of_lines = 0
while f.readline()!="":
number_of_lines += 1
print("Number of Lines in a file is ", number_of_lines)
Output - Number of Lines in a file is 18
Note - Before running these programs make sure you have your text file in the same directory where you have your python file. Otherwise, you need to give the correct path of a file
This code is also available on my GitHub you can check it out - Click Here
I hope this article was helpful to you and you learned from it. Make sure to check it out in future as I will be updating this blog and adding some more operation on files. Thank you for reading.
Comments
Post a Comment
If you have any questions do let me know and also give your valuable feedback for this blog.