aoaopython-aoaoglob-aoaoshutil

发布于 2024年04月17日

找出文件,文件复制移动

import shutil

shutil.copy('example.txt', 'destination_directory')

import shutil

shutil.move('source_directory', 'destination_directory')

import shutil

shutil.rmtree('directory_to_delete')

import shutil

shutil.make_archive('archive_name', 'zip', 'directory_to_compress')

import glob
import shutil
import os

def copy_files_with_new_suffixes(source_dir, target_dir):
    # 确保目标目录存在,如果不存在,则创建
    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    # 构造搜索路径
    search_path = os.path.join(source_dir, '*_2.*')
    
    # 遍历所有后缀为_2的文件
    files = glob.glob(search_path)
    for file in files:
        # 获取文件的基本名称和扩展名
        base_name = os.path.basename(file).rsplit('_', 1)[0]
        extension = file.split('.')[-1]

        # 生成新的文件名并复制文件
        for i in range(3, 7):
            new_file = f"{base_name}_{i}.{extension}"
            new_file_path = os.path.join(target_dir, new_file)
            shutil.copyfile(file, new_file_path)
            print(f"Copied '{file}' to '{new_file_path}'")

# 调用函数
source_directory = '/path/to/source/directory'  # 源目录路径
target_directory = '/path/to/target/directory'  # 目标目录路径
copy_files_with_new_suffixes(source_directory, target_directory)

import glob
import shutil
import os

def copy_files_with_new_suffixes(source_dir, target_dir):
    # 确保目标目录存在,如果不存在,则创建
    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    # 构造搜索路径
    search_path = os.path.join(source_dir, '*_2.*')
    
    # 遍历所有后缀为_2的文件
    files = glob.glob(search_path)
    for file in files:
        # 获取文件的基本名称和扩展名
        base_name = os.path.basename(file).rsplit('_', 1)[0]
        extension = file.split('.')[-1]

        # 生成新的文件名并复制文件
        for i in range(3, 7):
            new_file = f"{base_name}_{i}.{extension}"
            new_file_path = os.path.join(target_dir, new_file)
            shutil.copyfile(file, new_file_path)
            print(f"Copied '{file}' to '{new_file_path}'")

# 调用函数
source_directory = '/path/to/source/directory'  # 源目录路径
target_directory = '/path/to/target/directory'  # 目标目录路径
copy_files_with_new_suffixes(source_directory, target_directory)



评论