根据文件名的一部分将文件分隔到文件夹中

问题描述

我有一个文件夹,其中包含我编目的数千张图片,我需要根据部分名称将它们分成多个文件夹。名称的每个部分以“_”分隔。

典型的文件名是

DATE_OBJECTCODE_SUBCODE_X_01.jpeg

喜欢

210526 BL RL4_QRS Eur F699-1-2-2-180_6702_02_03

我想根据第二部分(QRS Eur F699-1-2-2-180 或其他任何部分)组织文件,因此所有具有该部分对应代码文件都将放置在具有该标题文件夹。

我对 python 很陌生,所以我自己尝试了一些代码,但无法弄清楚如何让系统识别文件名的一部分。

任何帮助将不胜感激!

解决方法

有了这个,您可以使用任何类型的 objectcode 名称,但请注意它不是您还想单独考虑的另一个 objectcode 名称的一部分:

import os,glob

# This assumes that this code is run inside
# the directory with the image files

# Path to the directory you will store 
# the directories with files (current here) 
path_to_files = os.getcwd()
objectcodes = ['QQS Eur F699-1','BL RL4_QRS Eur F699-1-2-7-5_379' ];

# For each objectcode
for obc in objectcodes:
    # Make a directory if it doesn't already exist
    file_dir = os.path.join(path_to_files,obc)
    if not os.path.isdir(file_dir):
        os.mkdir(file_dir)
        # If you need to set the permissions 
        # (this enables it all - may not be what you want)
        os.chmod(file_dir,0o777)

    # Then move all the files that have that objectcode 
    # in them and end with *.jpeg to the correct dir
    for fname in glob.glob('*' + obc + '*.jpg'):
        # Move the file
        os.rename(fname,os.path.join(file_dir,fname))

此代码不是解析文件名,而是在其中查找模式,而该模式就是您的 objectcode。它针对任意数量的 objectcodes 运行,如果您希望将来以不同的名称重复使用它,这将非常有用。

如前所述,如果有多个 objectcode 适合某个模式(我认为情况并非如此),那么您需要进行一些修改。

根据您的平台,您可能不需要更改您正在创建的目录的权限(我必须这样做),您还可以将权限修改为有效但更严格的内容(现在它只允许所有内容)。

> ,

所以你想要的是遍历一个包含图像的目录。对于每个图像,检查是否存在以 object_code(例如 QRS Eur F699-1-2-2-180)为名称的文件夹。如果没有,请创建文件夹。之后,将图像从当前文件夹(包含所有图像)移动到以 object_code 为名称的文件夹。为此,您可以使用模块 os 来循环您的文件并创建新文件夹。

请注意,这假定 object_code 始终是在 _ 上拆分文件名后的第二项。

path_images = 'path/to/my/images'

for image in os.listdir(path_images):
    if image.endswith('.png'):
        object_code = image.split("_")[1]  # object_code is something like QRS Eur F699-1-2-2-180
        
        if not path.isdir(object_code):  # Folder with this object_code does not yet exist,create it
            os.mkdir(object_code)
            
        # Move the file to the folder with the object_code name
        Path(f"{path_images}/{image}").rename(f"{path_images}/{object_code}/{image}")