python get line count of file code example

Example 1: python how to count the lines in a file

# Basic syntax:
count = len(open('/path/to/the/file.ext').readlines())

Example 2: python 3 text file leng

f = open("filename", "r") #Load file in any mode that's able to read, ie r, r+, w+ etc

#to get length
len(f.readlines())

#To iterate over each line
for line in f.readlines(): #file.readlines(), splits the file into a list, where each element is a seperate line
  print(line)

Example 3: how to know how much lines a file has using python

filename = "test.txt"
count = 0
with open(filename, 'r') as f:
    for line in f:
        count += 1
print("Total number of lines is:", count)

Tags:

Html Example