# Basic syntax:
count = len(open('/path/to/the/file.ext').readlines())
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.
'''
# Let's use a text file called file.txt
# the file contains 5 lines of some programming languages in use today:
$ cat file.txt
#Output:
# JavaScript
# Java
# C
# Python
# C#
# Method 1 'wc'
# 'wc' command can be used to find the number of lines, characters,
# words, and bytes of a file.
$ wc -l file.txt
# Or
$ wc -l < file.txt
# Or
$ wc -l file.txt
# Output:
# 10 file.txt
# OR
# Method 2 - 'sed'
# 'sed' is a stream editor that can be used to perform basic text transformation
# of an input file.
# This command is mostly used for find-and-replace functionality and
# can also be used to find the number of lines of a specified file.
$ sed -n '=' file.txt
# Output:
# 1
# 2
# 3
# 4
# 5
# Or
# sed -n '$=' which gives the overall number of lines
$ sed -n '$=' file.txt
# Output:
# 5
# open file in read mode
with open(r"E:demosfiles
ead_demo.txt", 'r') as fp:
for count, line in enumerate(fp):
pass
print('Total Lines', count + 1)
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)