以下 Python 代码实现了将 /mnt/disk1/lh/landmark/data 目录下的文件夹分类,将开头为英文字母的文件夹中的文件放入 /mnt/disk1/lh/landmark/erfen/negative,其他文件夹中的文件放入 /mnt/disk1/lh/landmark/erfen/positive,并从 0 开始重命名文件:

import os
import shutil

source_dir = '/mnt/disk1/lh/landmark/data'
negative_dir = '/mnt/disk1/lh/landmark/erfen/negative'
positive_dir = '/mnt/disk1/lh/landmark/erfen/positive'

if not os.path.exists(negative_dir):
    os.makedirs(negative_dir)

if not os.path.exists(positive_dir):
    os.makedirs(positive_dir)

count = 0

for folder_name in os.listdir(source_dir):
    folder_path = os.path.join(source_dir, folder_name)
    if os.path.isdir(folder_path) and folder_name[0].isalpha():
        destination_dir = negative_dir
    else:
        destination_dir = positive_dir

    for file_name in os.listdir(folder_path):
        file_path = os.path.join(folder_path, file_name)
        if os.path.isfile(file_path):
            new_file_name = str(count) + os.path.splitext(file_name)[1]
            new_file_path = os.path.join(destination_dir, new_file_name)
            shutil.copy(file_path, new_file_path)
            count += 1

这段代码首先定义了源目录 source_dir,以及目标目录 negative_dirpositive_dir。然后,它会检查目标目录是否存在,若不存在则创建它们。

接下来,通过遍历源目录中的文件夹,判断文件夹名字的首字母是否为英文字母。如果是,则将文件夹中的文件复制到 negative_dir 目录中,否则复制到 positive_dir 目录中。同时,它会将文件重命名为从 0 开始的数字命名。

注意,这段代码假定源目录中只包含文件夹,而不包含其他文件。如果源目录中还包含其他类型的文件,你可能需要添加一些额外的逻辑来处理它们。

Python 脚本:根据文件夹名称将文件分类并重命名

原文地址: https://www.cveoy.top/t/topic/mpP0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录