简体   繁体   English

按名称将文件组织到 Python 中的分类子文件夹中

[英]Organize files by name into categorical subfolders in Python

I need an algorithm that organize some files in a directory by the name of the file.我需要一种算法,通过文件名组织目录中的一些文件。

I wrote some categories:我写了一些类别:

Bread = ["bread", "pizza", "spaghetti"]
Meat = ["hamburger", "meat", "porkchop"]

If a file name is hamburger recipe.txt , I need this file to be moved to a particular directory called Meat .如果文件名为hamburger recipe.txt ,我需要将此文件移动到名为Meat的特定目录中。

If another file name is bread with vegetables.doc , this file will be moved to the folder named Bread .如果另一个文件名为bread with vegetables.doc ,则该文件将移动到名为Bread的文件夹中。

I tried to write this, but it doesn't work:我试图写这个,但它不起作用:

meat = ["hamburger", "meat", "porkchop"]

for filename in os.listdir(path):
    if meat in filename:
        os.rename(filename, "Meat/" + filename)

Can you help me?你能帮助我吗?

You have to test if any of the food items in your meat category appears in the filename:您必须测试您的meat类别中的任何食品是否出现在文件名中:

meat = ["hamburger", "meat", "porkchop"]

for filename in os.listdir(path):
    if any(food in filename for food in meat):
        os.rename(filename, "Meat/" + filename)

This is the right idea.这是正确的想法。 I'd use a dictionary to make categories easier to manipulate.我会使用字典使类别更易于操作。 While it makes sense to map categories to keywords for organizational purposes, lookups will be faster by inverting the dict.虽然出于组织目的将 map 类别转换为关键字是有意义的,但通过反转 dict 查找会更快。 At that point, we can split each filename on non-word characters, check our keyword lookup table for a match, create any nonexistent directories and move files as necessary.那时,我们可以将每个文件名拆分为非单词字符,检查我们的关键字查找表是否匹配,创建任何不存在的目录并根据需要移动文件。

import os
import re

path = "."
categories = {
    "meat": ["hamburger", "meat", "porkchop"],
    "bread": ["bread", "pizza", "spaghetti"]
} 
keywords = {}

for k, v in categories.items():
    for x in v:
        keywords[x] = k

for filename in [x for x in os.listdir(path) if os.path.isfile(x)]:
    for term in [x for x in re.split(r"\W+", filename.lower()) if x in keywords]:
        dest = os.path.join(keywords[term], filename)
        src = os.path.join(path, filename)

        try:
            if not os.path.exists(keywords[term]):
                os.makedirs(keywords[term])

            os.rename(src, dest)
        except (FileNotFoundError, FileExistsError) as e:
            print(e)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM