# Basic syntax:
count = len(open('/path/to/the/file.ext').readlines())
fname = "test.txt"
count = 0
with open(fname, 'r') as f:
for line in f:
count += 1
print("Total number of lines is:", count)
num_lines = sum(1 for line in open('myfile.txt'))
def countlines(fname,mode='r+'):
count=0
with open(fname) as f:
for _ in f:
count += 1
print('total number of lines in file : ',count)
countlines('file1.txt')
##########################
with open('file1.txt') as f:
print(sum(1 for _ in f))
###########################
'''You can use len(f.readlines()),
but this will create an additional list in memory,
which won't even work on huge files that don't fit in memory.
'''
num_lines = sum(1 for line in open('myfile.txt'))
# Notice: Problem with this solution is that it won't
# count empty line if it is at end of file.
# You can do it by iterating through a simple for loop
fhand = open('path and the file name')
count = 0
for line in fhand:
count += 1
print('The number of lines in the file is:', count)