合并、拼接一个文件夹及其所有子文件夹中的代码文件(删除空行;软著源代码)

拼接一个文件夹和子文件夹中的全部代码文件

写python代码,拼接一个文件夹及其子文件夹中的全部代码文件。

拼接全部的py文件,vue文件,js文件

 

拼接一个文件夹及其所有子文件夹中的代码文件

以下是一个 Python 脚本,用于递归遍历指定文件夹及其子文件夹,并将所有代码文件(如 .py.js.html.css 等)的内容拼接成一个字符串输出:

import os

def concatenate_code_files(root_folder, extensions=None):
    """
    拼接指定文件夹及其子文件夹中的全部代码文件内容

    :param root_folder: 根文件夹路径
    :param extensions: 需要拼接的文件扩展名列表(如 ['.py', '.js']),默认为常见代码文件扩展名
    :return: 拼接后的字符串
    """
    if extensions is None:
        extensions = ['.py', '.js', '.html', '.css', '.vue' ]

    result = []

    for foldername, subfolders, filenames in os.walk(root_folder):
        for filename in filenames:
            # 检查文件扩展名是否在目标列表中
            if any(filename.endswith(ext) for ext in extensions):
                filepath = os.path.join(foldername, filename)
                try:
                    with open(filepath, 'r', encoding='utf-8') as f:
                        # 添加文件路径作为注释分隔
                        #result.append(f"\n\n{'='*50}\n")
                        #result.append(f"# File: {filepath}\n")
                        #result.append(f"{'='*50}\n\n")
                        result.append(f.read())
                except Exception as e:
                    print(f"Error reading {filepath}: {e}")

    return ''.join(result)

# 使用示例
if __name__ == "__main__":
    folder_path = input("请输入文件夹路径: ").strip()
    if os.path.isdir(folder_path):
        concatenated_code = concatenate_code_files(folder_path)

        # 输出到控制台(对于大文件可能不友好)
        #print(concatenated_code)

        # 或者保存到文件
        output_file = os.path.join(folder_path, "concatenated_code.txt")
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(concatenated_code)
        print(f"\n所有代码已拼接保存到: {output_file}")
    else:
        print("错误: 指定的路径不是有效文件夹")

 

 

图片

请输入文件夹路径: E:\_prjct\传感器集成\软著\代码拼接\前端

所有代码已拼接保存到: E:\_prjct\传感器集成\软著\代码拼接\前端\concatenated_code.txt

Process finished with exit code 0

 

写Python代码,把文件中的空行全部删除,把全是空格或Tab的行全部删除。

 

import re

def remove_empty_lines(input_file, output_file=None, in_place=False):
    """
    删除文件中的空行和全是空格/Tab的行

    :param input_file: 输入文件路径
    :param output_file: 输出文件路径(如果in_place为False)
    :param in_place: 是否直接修改原文件(默认False)
    """
    if in_place:
        output_file = input_file
    elif output_file is None:
        output_file = input_file + ".cleaned"

    try:
        with open(input_file, 'r', encoding='utf-8') as f_in:
            lines = f_in.readlines()

        # 处理每一行:去除空白行(包括只有空格/Tab的行)
        cleaned_lines = []
        for line in lines:
            # 如果行不是空行且不全是空白字符,则保留
            if line.strip() != "":
                cleaned_lines.append(line)

        with open(output_file, 'w', encoding='utf-8') as f_out:
            f_out.writelines(cleaned_lines)

        print(f"处理完成!结果已保存到: {output_file}")
        print(f"原始行数: {len(lines)},处理后行数: {len(cleaned_lines)}")

    except Exception as e:
        print(f"处理文件时出错: {e}")

# 使用示例
if __name__ == "__main__":
    file_path = input("请输入文件路径: ").strip()
    choice = input("直接修改原文件?(y/n,默认n): ").strip().lower()

    if choice == 'y':
        remove_empty_lines(file_path, in_place=True)
    else:
        output_path = input("请输入输出文件路径(留空则自动添加.cleaned后缀): ").strip()
        remove_empty_lines(file_path, output_file=output_path if output_path else None)

 

 

请输入文件路径: E:\_prjct\传感器集成\软著\代码拼接\前端\concatenated_code.txt
直接修改原文件?(y/n,默认n): y
处理完成!结果已保存到: E:\_prjct\传感器集成\软著\代码拼接\前端\concatenated_code.txt
原始行数: 31535,处理后行数: 29013

 

合并py文件,并且删除空行【可行】

import os

def concatenate_code_files(root_folder, extensions=None):
    """
    拼接指定文件夹及其子文件夹中的全部代码文件内容

    :param root_folder: 根文件夹路径
    :param extensions: 需要拼接的文件扩展名列表(如 ['.py', '.js']),默认为常见代码文件扩展名
    :return: 拼接后的字符串
    """
    if extensions is None:
        extensions = ['.py' ] # , '.js', '.html', '.css', '.vue'

    result = []

    for foldername, subfolders, filenames in os.walk(root_folder):
        for filename in filenames:
            # 检查文件扩展名是否在目标列表中
            if any(filename.endswith(ext) for ext in extensions):
                filepath = os.path.join(foldername, filename)
                try:
                    with open(filepath, 'r', encoding='utf-8') as f:
                        # 添加文件路径作为注释分隔
                        #result.append(f"\n\n{'='*50}\n")
                        #result.append(f"# File: {filepath}\n")
                        #result.append(f"{'='*50}\n\n")
                        result.append(f.read())
                except Exception as e:
                    print(f"Error reading {filepath}: {e}")

    return ''.join(result)

# 使用示例
if __name__ == "__main__":
    folder_path = input("请输入文件夹路径: ").strip()
    if os.path.isdir(folder_path):
        concatenated_code = concatenate_code_files(folder_path)

        # 输出到控制台(对于大文件可能不友好)
        #print(concatenated_code)

        # 或者保存到文件
        output_file = os.path.join(folder_path, "concatenated_code.txt")
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(concatenated_code)
        print(f"\n所有代码已拼接保存到: {output_file}")
    else:
        print("错误: 指定的路径不是有效文件夹")

    try:
        # 读取abc.txt文件内容
        with open(output_file, 'r', encoding='utf-8') as infile:
            lines = infile.readlines()

        # 过滤空行(空行定义:strip()后为空字符串的行)
        # strip()会自动去除字符串前后的空格、Tab、换行符等空白字符
        non_empty_lines = [line for line in lines if line.strip()]

        # 将过滤后的内容写入ddd.txt
        with open('ddd.txt', 'w', encoding='utf-8') as outfile:
            outfile.writelines(non_empty_lines)

        print("处理完成,已将结果保存到ddd.txt")

    except FileNotFoundError:
        print("错误:未找到abc.txt文件,请检查文件是否存在")
    except Exception as e:
        print(f"处理过程中发生错误:{str(e)}")

 

posted @ 2025-11-13 11:37  emanlee  阅读(17)  评论(0)    收藏  举报