背景
写了一堆.cs文件
想看看一共写了多少行
代码
import os
import chardet
# Check if a file has the given extension
def has_extension(file, extension):
return os.path.splitext(file)[1] == extension
# Count the number of non-empty lines in a file
def count_lines_of_code(file):
with open(file, 'rb') as f:
result = chardet.detect(f.read())
encoding = result['encoding']
with open(file, 'r', encoding=encoding) as f:
lines = [line.strip() for line in f if line.strip()]
return len(lines)
# Get all files with the given extension in the current directory
def get_files_with_extension(extension):
files = [file for file in os.listdir('.') if os.path.isfile(file) and has_extension(file, extension)]
return files
if __name__ == '__main__':
files = get_files_with_extension('.cs')
total_lines = 0
for file in files:
lines = count_lines_of_code(file)
print(f'{file}: {lines} lines')
total_lines += lines
print(f'Total lines of code in .cs files: {total_lines}')