Count Python Lines in Directory

  • Share this:

Code introduction


Calculate the total number of lines in all Python files within a specified directory.


Technology Stack : os, re, sys, time

Code Type : Function

Code Difficulty : Intermediate


                
                    
import os
import re
import sys
import time

def count_lines_in_files(directory):
    total_lines = 0
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.py'):
                file_path = os.path.join(root, file)
                with open(file_path, 'r') as f:
                    total_lines += len(f.readlines())
    return total_lines                
              
Tags: