python查找不同于foldernam的文件名

2024-04-25 14:40:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我的公司有文件名为

"3688-35(DUSTY GREY-BLK).jpg"
"3688-36A(SLIVER).jpg"
"..."

应该放在“3688”文件夹中。你知道吗

年复一年,我面对的是6位数的图片和3500个文件夹,其中有无数需要检查的图片放错了地方

所以我想我可以写一个脚本,只能列出错误放置的文件和文件夹之类的

"1111/1112.jpg"
"1234/1243.jpg"

在我做了一些搜索之后,我发现match filenames to foldernames then move files是我所需要的,但是我不能根据我的需要修改答案,因为文件名模式。你知道吗

一开始我很固执,但我认为https://pymotw.com/2/glob/可以在列表和https://linux.die.net/man/3/fnmatch上做一些技巧?你知道吗


Tags: 文件https脚本文件夹文件名地方错误图片
1条回答
网友
1楼 · 发布于 2024-04-25 14:40:57

我已经解决了我的问题。你知道吗

from glob import glob
import logging, time, os

def listdirs(path):
    return [d for d in os.listdir(path) if os.path.isdir(d)]

def find_pics():
    folders = listdirs(".")
    for dir in folders:
        time.sleep(0.3)
        pics = os.listdir(dir)
        for pic in pics:
            if pic.endswith(".jpg"):
                if dir not in pic:
                    logging.warning(dir + ' / ' + pic)
                else:
                    pass
            else:
                pass
    return

def main():
    logging.basicConfig(filename='wrong_placed.log', filemode='w', level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s \n')
    logging.debug("Starting to check is the picture wrong placed.")
    find_pics()
    return

if __name__ == '__main__':
    main()

相关问题 更多 >