File Handling with Python || Python programming tutorial


In File Handling, we will be working on a file in our computer and doing various operations on it. Check out my previous blog on Python programming if you want to learn from scratch.

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

  1. First, we need to open that text file in our python program using a function open().
  2. The open() function will take two arguments filename and set our intentions.
  3. 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
  4. 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

Popular posts from this blog

Reinforcement Learning - An Introduction || Getting started with RL

Pose Estimation || Application of Computer Vision and Deep Learning

Getting Started with your first Machine Learning Algorithm - Linear Regression || First step towards ML