首先是白嫖以下大神的代码:统计python代码行数小工具_linecount工具-CSDN博客
然后,让ChatGPT帮我改为如下的完整代码(第三次修正:))
import os
from tkinter import Tk, Label, Button, filedialog
import sys
import codecs
import chardet
import shutil
from datetime import datetime
def open_file(file_path,forced_encoding):
try:
# 检测文件编码
with open(file_path, 'rb') as f:
contents = f.read()
result = chardet.detect(contents)
encoding = result['encoding']
if forced_encoding != '':
encoding = forced_encoding
file = open(file_path, 'r', encoding=encoding)
return file
except Exception as e:
print(f"处理文件 {file_path} 时出现错误:{e}")
return None
def count_lines_in_file(file_path,forced_encoding):
count = 0
in_multi_line_comment = False
file = open_file(file_path,forced_encoding)
if not file:
raise Exception(f'出现错误Error reading file: {file_path}')
with file:
for line in file:
clean_line = line.strip()
if in_multi_line_comment:
if "*/" in clean_line:
in_multi_line_comment = False
continue
elif not clean_line or clean_line.startswith('//'):
continue
elif clean_line.startswith('/*'):
in_multi_line_comment = True
continue
count += 1
return count
def count_lines_in_directory(directory):
total_count = 0
now = datetime.now()
#current_dir = os.getcwd() # 获取当前工作目录
#target_dir = os.path.join(current_dir, '{}'.format(now.strftime("%Y-%m-%d_%H-%M-%S"))) # 在当前路径下创建 temp 目录
target_dir = 'D:/Temp/{}'.format(now.strftime("%Y-%m-%d_%H-%M-%S"))
# 创建 temp 目录
os.makedirs(target_dir, exist_ok=True)
for dirpath, dirnames, filenames in os.walk(directory):
for filename in filenames:
if filename.endswith('.c') or filename.endswith('.h'):
file_path = os.path.join(dirpath, filename)
try:
count = count_lines_in_file(file_path,'')
#print(f'{file_path}: {count}')
total_count += count
except Exception as e:
print(f'aaaaaaaaaaaaaaaaaaa{file_path}:{str(e)}')
# 复制文件到 temp 目录
file_name = os.path.basename(file_path)
target_file_path = os.path.join(target_dir, file_name)
shutil.copy(file_path, target_file_path)
for dirpath, dirnames, filenames in os.walk(target_dir):
for filename in filenames:
if filename.endswith('.c') or filename.endswith('.h'):
file_path = os.path.join(dirpath, filename)
try:
# 将文件转换为 UTF-8 编码
with open(file_path, 'rb') as file:
content = file.read() # 读取二进制文件内容
try:
content_decoded = content.decode('utf-8') # 尝试使用UTF-8解码
except UnicodeDecodeError:
content_decoded = content.decode('latin-1') # 如果解码出错,尝试使用latin-1解码
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content_decoded) # 将解码后的内容写入文件
except Exception as e:
print(f'bbbbbbbbbbbbbbbbbbb{file_path}:{str(e)}')
for dirpath, dirnames, filenames in os.walk(target_dir):
for filename in filenames:
if filename.endswith('.c') or filename.endswith('.h'):
file_path = os.path.join(dirpath, filename)
try:
count = count_lines_in_file(file_path,'')
#print(f'{file_path}: {count}')
total_count += count
except Exception as e:
print(f'ccccccccccccccccccccc{file_path}:{str(e)}')
return total_count
# Windows APP design
windows = Tk()
windows.title("Code Line Counting Tool")
windows.geometry("450x450")
def clicked():
directory = filedialog.askdirectory()
L2.configure(text="directory: %s"
%directory)
L1.configure(text="The total number of code lines in files %s lines"
%(count_lines_in_directory(directory)))
# UI layout
button = Button(windows,text="Select folder and submit",command=clicked)
button.pack()
L2 = Label(windows,text = "",bg='white',width=200,height=10)
L2.pack()
L1 = Label(windows,text = "",bg='white',width=200,height=10)
L1.pack()
windows.mainloop()
特点:支持三种编码格式,你可以继续加其它编码。简单直接 :)