Algorithm


  1. Open the File:

    • Use the open() function to open the file in read mode.
    • Handle any potential exceptions, such as FileNotFoundError.
  2. Initialize Line Count:

    • Set a variable (e.g., line_count) to zero. This will be used to store the count of lines in the file.
  3. Read Lines:

    • Use a loop to iterate through each line in the file.
    • Increment the line_count for each line read.
  4. Display or Return the Result:

    • Print or return the line_count to show the total number of lines in the file.
  5. Close the File:

    • Close the file using the close() method to free up system resources.

 

Code Examples

#1 Code Example with Python Programming

Code - Python Programming

try:
    # Step 1: Open the File
    with open("filename.txt", "r") as file:
        # Step 2: Initialize Line Count
        line_count = 0

        # Step 3: Read Lines
        for line in file:
            line_count += 1

        # Step 4: Display or Return the Result
        print("Total lines in the file:", line_count)

except FileNotFoundError:
    print("File not found.")
except Exception as e:
    print("An error occurred:", e)
finally:
    # Step 5: Close the File
    file.close()
Copy The Code & Try With Live Editor

#2 Code Example- Using a for loop

Code - Python Programming

def file_len(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1

print(file_len("my_file.txt"))
Copy The Code & Try With Live Editor

Output

x
+
cmd
3

#3 Code Example- Using list comprehension

Code - Python Programming

num_of_lines = sum(1 for l in open('my_file.txt'))

print(num_of_lines)
Copy The Code & Try With Live Editor

Output

x
+
cmd
3
Advertisements

Demonstration


Python Programing Example to Get Line Count of a File-DevsEnv