Count Lines in Text File Python Program

By | March 30, 2020

Topic: Count Lines in Text File Python Program

Count Lines in Text File Python Program

Count Lines in Text File Python Program

# Python program to count 
# number of lines in a file
# Input filename, open it in 
# read mode. display its cntents 
# count and display number of lines
# www.EasyCodeBook.com

file_name = input("Enter file name:")

file1 = open(file_name, "r")

line_count = 0
print("Contents of file " + file_name + " are:")

# display and count number of lines
for line in file1:
    print(line, end='')
    line_count+=1

print('\n\nTotal Number of lines in this file are = ' + str(line_count))

file1.close()

 

How this Program works?

  • First of all we will show a message to the to enter the name of the file.
  • The user will input a valid file name.
  • We use input() function of Python for the above mentioned task.
  • open() function will be used to open the given file in read mode, since we supply two arguments, the file name and an opening mode “r”.
  • Set a line_count variable to zero.
  • We will use a for loop to read and print contents of the file:
  • We will read the given file line by line.
  • We will count each line by adding a 1 to line_count for each iteration of the loop
  • We will show the total number of lines in the text file.

Note: This is to be noted that a file with name “example.txt” must be present at d: drive. As an example we create a file with name example.txt on D: drive with the following contents, as shown in the above image:

this is example text file
this is line 2
this is last line

 

Output

Enter file name:d://example.txt
Contents of file d://example.txt are:
this is example text file
this is line 2
this is last line

Total Number of lines in this file are = 3

You will also like the following Python File Programs:

 

2 thoughts on “Count Lines in Text File Python Program

  1. Pingback: Python File Copy Program using shutil.filecopy | EasyCodeBook.com

  2. Pingback: Python Count Words in Text File | EasyCodeBook.com

Leave a Reply

Your email address will not be published. Required fields are marked *