Tuesday, 21 September 2021

Python: Count number of lines in a file

'len(fp.readlines())' method is used to get number of lines in a file.

myfile.txt 

Test line 1
Test line 2


count_number_of_lines_in_file.py

import os

file_to_read = 'myfile.txt'
path = '/Users/Shared/data'

with open(os.path.join(path, file_to_read), 'r') as fp:
    no_of_lines = len(fp.readlines())
    print('Number of lines in a file : ', no_of_lines)

 

Output

Number of lines in a file :  2

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment