当前目录下所有txt文件所有的账户统计

查看 12|回复 0
作者:鼠八爷   
这玩意一般人用不着,
主要功能是扫描当前目录下的所有 .txt 文件,并统计每个文件中包含冒号 :(可以改成----) 且去除首尾空白后不为空的行数,输出结果。


QQ20250203-025102.png (31.16 KB, 下载次数: 0)
下载附件
2025-2-3 02:52 上传

[Python] 纯文本查看 复制代码import os
import re
def count_accounts_in_file(file_path):
    count = 0
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            for line in file:
                line = line.strip()
                if line and ':' in line:
                    count += 1
    except Exception as e:
        print(f"读取文件 {file_path} 时出错: {e}")
    return count
def scan_directory(directory):
    txt_files = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.txt'):
                txt_files.append(os.path.join(root, file))
    def get_first_number(filename):
        match = re.search(r'\d+', os.path.basename(filename))
        if match:
            return int(match.group())
        return float('inf')
    txt_files.sort(key=get_first_number)
    result = ""
    for file_path in txt_files:
        file = os.path.basename(file_path)
        account_count = count_accounts_in_file(file_path)
        line = f" {file} : {account_count}个\n"
        result += line
        print(line.strip())
    return result
if __name__ == "__main__":
    print("欢迎使用本程序")
    current_directory = os.getcwd()
    while True:
        choice = input("是否开始扫描目录?(y/n): ")
        if choice.lower() == 'y':
            scan_result = scan_directory(current_directory)
            output_file_path = os.path.join(current_directory, "结果.txt")
            try:
                with open(output_file_path, 'w', encoding='utf-8') as output_file:
                    output_file.write(scan_result)
                print(f"扫描结果已保存到 {output_file_path}")
            except Exception as e:
                print(f"保存结果到文件时出错: {e}")
        elif choice.lower() == 'n':
            print("程序已退出。")
            break
        else:
            print("无效的输入,请输入 'y' 或 'n'。")

文件, 目录下

您需要登录后才可以回帖 登录 | 立即注册

返回顶部