Java项目替换包名

Java项目替换包名

处理单级目录

import os

def process_directory(path):
    for root, dirs, files in os.walk(path, topdown=False):
        # 处理文件
        for name in files:
            file_path = os.path.join(root, name)
            new_name = name.replace('xxxx', 'ruphy').replace('XxXx', 'Ruphy').replace('Xxxx', 'Ruphy')
            new_file_path = os.path.join(root, new_name)
            if name != new_name:
                # 检查新文件名是否已存在
                if not os.path.exists(new_file_path):
                    os.rename(file_path, new_file_path)
            # 如果是文本文件,替换内容
            if name != 'node_modules' and new_name.endswith(('.txt', '.properties', '.java', '.xml', '.vue', '.js', '.md', '.yml', '.css', '.wxss', '.json', '.wxml', '.html', '.htm', '.vm', '.sql', 'Dockerfile')):
                try:
                    with open(new_file_path, 'r', encoding='utf-8') as file:
                        content = file.read()
                    with open(new_file_path, 'w', encoding='utf-8') as file:
                        file.write(content.replace('xxxx', 'ruphy').replace('://ruphy', '://xxxx').replace('XxXx', 'Ruphy').replace('Xxxx', 'Ruphy'))
                except UnicodeDecodeError:
                    # 如果文件不是 UTF-8 编码,可以尝试其他编码或忽略错误
                    print(f"Warning: Could not decode file {new_file_path} as UTF-8. Skipping.")

        # 处理目录
        for name in dirs:
            dir_path = os.path.join(root, name)
            new_name = name.replace('xxxx', 'ruphy').replace('XxXx', 'Ruphy').replace('Xxxx', 'Ruphy')
            new_dir_path = os.path.join(root, new_name)
            if name != new_name:
                # 检查新目录名是否已存在
                if not os.path.exists(new_dir_path):
                    os.rename(dir_path, new_dir_path)
                # 不处理空目录的删除,因为存在冲突
            # 检查是否为空目录且名称为xxxx,如果是则删除
            elif name == 'xxxx' and not os.listdir(dir_path):
                os.rmdir(dir_path)
            elif name == 'XxXx' and not os.listdir(dir_path):
                os.rmdir(dir_path)

# 指定要处理的目录路径
current_directory = os.getcwd()
process_directory(current_directory)

处理多级目录

import os
import shutil

def replace_directory_and_content(root_dir):
    for subdir, dirs, files in os.walk(root_dir):
        # Debug: Print current directory being processed
        print(f"Processing directory: {subdir}")

        # Check if 'cn/xxxx' exists in the current path
        if 'cn\\xxxx' in subdir:
            # Construct the new path by replacing 'cn/xxxx' with 'com'
            new_subdir = subdir.replace('cn\\xxxx', 'com')
            
            # Debug: Print new directory path
            print(f"New directory path: {new_subdir}")

            # Create the new directory structure
            os.makedirs(new_subdir, exist_ok=True)

            # Move files and directories from old to new structure
            for item in os.listdir(subdir):
                old_item_path = os.path.join(subdir, item)
                new_item_path = os.path.join(new_subdir, item)

                if os.path.isdir(old_item_path):
                    # If it's a directory, we'll handle its contents recursively later
                    continue
                elif os.path.isfile(old_item_path):
                    # Move the file and then replace content
                    shutil.move(old_item_path, new_item_path)
                    
                    # Replace 'cn.xxxx' with 'com' in the file content
                    try:
                        with open(new_item_path, 'r', encoding='utf-8') as file:
                            content = file.read()
                        
                        new_content = content.replace('cn.xxxx', 'com')
                        
                        with open(new_item_path, 'w', encoding='utf-8') as file:
                            file.write(new_content)

                        print(f"Processed file: {new_item_path}")
                    except Exception as e:
                        print(f"Error processing file {new_item_path}: {e}")

            # After moving all files, try to remove the old directory
            try:
                os.rmdir(subdir)
                print(f"Removed old directory: {subdir}")
            except OSError:
                # Directory is not empty, might contain subdirectories we'll handle later
                print(f"Could not remove old directory: {subdir} (not empty?)")

# Start the replacement from the current directory
current_directory = os.getcwd()
print(f"Starting in directory: {current_directory}")
replace_directory_and_content(current_directory)

print("Replacement completed.")

删除空目录

import os

def remove_empty_directories(root_dir):
    # Walk the directory tree bottom-up
    for subdir in sorted(os.listdir(root_dir), reverse=True):
        path = os.path.join(root_dir, subdir)
        
        if os.path.isdir(path):
            # Recursively remove empty subdirectories
            remove_empty_directories(path)
            
            # Try to remove the directory; if it's empty, it will be removed
            try:
                os.rmdir(path)
                print(f"Removed empty directory: {path}")
            except OSError:
                # Directory is not empty
                pass

def start_removal(start_dir):
    # Start the removal process from the specified directory
    remove_empty_directories(start_dir)

# Set the root directory from which to start removing empty directories
root_directory = os.getcwd()  # Adjust this path as needed

# Get the absolute path if running from a different location

start_removal(root_directory)

print("Empty directory removal completed.")
posted @ 2024-12-24 01:10  明月心~  阅读(37)  评论(0)    收藏  举报