Working with Files in Python

Aryan Irani
6 min readMar 9, 2021

Welcome !

In this blog we are going to play with some txt files using python. I am going to be doing the following 3 example:

(1) Print the number of lines in the txt file
(2) Print the count of each word in the file
(3) Print the line number next to each line in the file

So let’s get started.

Print the number of lines in the txt file

This is the first example that I will be explaining. This the output that we have to achieve in the end.

Here you can see that the number of lines in the txt file has been printed. Let’s take a look at the code.

This is the code that is used in this example.

This is the txt file that we are going to use in this example. Now let’s take a look at the code step-by-step.

# READ FILEdf = open("file1.txt")# read fileread = df.read()

So first we are going to start out by opening the txt file that we need to read. After opening the file, we need to access the contents of the file. To do that we are going to use the read function and assign the content to a variable.

# count number of lines in the fileline = 1for word in read:
if word == '\n':
line += 1
print("Number of lines in file is: ", line)

First we are going to initialize the line variable. This variable will contain the number of lines in the file. Next we are going to check whether there is a new line in the file and add it to the line variable. This will continue until it reaches the last line of the file.

Let’s move to the next example.

Print the count of each word in the file

This is the second example that I will be explaining. This the output that we have to achieve in the end.

Here you can see the number of times each word appears in the file. Let’s take a look at the code.

This is the code that is used in this example.

This is the txt file that we are going to use in this example. Now let’s take a look at the code step-by-step.

text = open("file1.txt", "r")d = dict()

First we are going to open the file in read mode and store the contents of the file in a variable text . Then we are going to create an empty dictionary.

for line in text:
line = line.strip()
line = line.lower()
words = line.split(" ")

for word in words:
if word in d:
d[word] = d[word] + 1
else:
d[word] = 1

Here we are going to use three functions :

  • strip : Here we are going to remove the white spaces present in the file
  • lower : Here we are going to convert all the words in lowercase to reduce any issues.
  • split : Here we are going to split the words with a space.

Next we are going to iterate over each word in the line and check if the word is in the dictionary, and if it is present then it will increase the count of the word by 1, and if it is not present it will get added to the dictionary.

for key in list(d.keys()):
print(key, ":", d[key])

Here we are going to use the for loop and print the word and the number of times it is present in the txt file.

Let’s move to the next example.

Print the line number next to each line in the file

This is the last example that I will be explaining. This is the output that we have to achieve in the end.

Here you can see the line number has been printed next to each line. Let’s take a look at the code.

This is the txt file that we are going to use in this example. Now lets take a look at the code step-by-step.

FileName = "file1.txt"f  = open(FileName,"r")
fileContent = f.read()

First we are going to assign the file to a variable. Then we are going to open the file in read mode. Then we are going to get the contents of the file and assign it to a variable.

number_of_lines = 0line_by_line = fileContent.split("\n")
number_of_lines = len(line_by_line)
print("The number of lines in the file are : ")
print(number_of_lines)

First we have declared the number of lines as zero. Then we are going to split the contents of the file and put them in a list. Then we are going to get the length of the list and assign it to variable number_of_lines . Then we are going to print it and check whether we have got the correct number of lines present in the txt file.

newContents = ""lineIndex = 1for line in line_by_line:
newContents = newContents + "Line #" +str(lineIndex) + ": " + line + "\n"
lineIndex=lineIndex+1

Here we are going to declare the line index to 1. Then we are going to use a for loop and and going to first put the contents of the file, then put the number and lines that are present in the file. For each line the link index will be incremented after each line has been changed.

fNewFile = open("NumberedFile-" + FileName,"w")fNewFile.write(newContents)print("File has been created successfully")

After making changes to the contents of the file, we are going to create a new txt file that is going to store the contents of the file. So first we are going to open a file and give it a name. Then using the write function we are going to store the new contents of the file in it. At the end of the execution, you will see that a new txt file has been created.

This is txt that you will see. Here you see that the line number has been printed in front of each line.

This is all for this blog. I hope you have understood how to carry out basic functions on txt file using python. You can send your feedback on aryanirani123@gmail.com .

--

--