Count the Number of Lines in a File in Python

Python Program to Count the Number of Lines in a File Using readline() Function

# Python Program to Count the Number of Lines in a File Using readline() Function

#open the file to read
with open(r"file.txt", 'r') as fp:
# readlines() function to read all the lines at a single go
	lines = len(fp.readlines())
	print('Total Number of lines:', lines)

Output:

Total Number of lines: 5

Python Program to Count the Number of Lines in a File Using enumerate

# Python Program to Count the Number of Lines in a File Using enumerate

# open the file to read
with open(r"file_one.txt", 'r') as fp:
# enumerate() function adds a counter to an iterable and returns it in a format  of enumerating objects
    for count, line in enumerate(fp):
        pass
print('Total Number of lines:', count + 1)


Output:

Total Number of lines: 8

Python Program to Count the Number of Lines in a File Using counter

# Python Program to Count the Number of Lines in a File Using counter

# Opening a file
file = open("one.txt", "r")
Counter = 0
 
# Reading from file
Content = file.read()
CoList = Content.split("\n")
 
for i in CoList:
    if i:
        Counter += 1
 
print("This is the number of lines in the file")
print(Counter)

Output:

This is the number of lines in the file
4

Python Program to Count the Number of Lines in a File Using sum() Function

# Python Program to Count the Number of Lines in a File Using sum() Function

# Reading from file
with open(r"file1.txt", 'r') as fp:
	lines = sum(1 for line in fp)
	print('Total Number of lines:', lines)

Output:

Total Number of lines: 6

About The Author

Leave a Reply