简体   繁体   English

Python:将文件名与同一目录中的文件夹名进行比较

[英]Python : Comparing file name with folder name in same directory

I have a folder with lot of zip files and the extracted folders for the same. 我有一个包含很多zip文件的文件夹,并且提取了相同的文件夹。 The folder has become so much clustered . 该文件夹已成簇。

Is there any way to compare the zipped files name with the EXTRACTED folders name in the same directory ? 有什么方法可以将压缩文件名与同一目录中的EXTRACTED文件夹名进行比较?

i want to delete the EXTRACTED folders if they have a .zip file in the same directory. 我要删除EXTRACTED文件夹,如果它们在同一目录中有一个.zip文件。

Hope it help 希望对你有帮助

import os
import shutil

for file in os.listdir(path_to_dir):
    if os.path.isdir(file + ".zip"):
        shutil.rmtree(file)

You can try something like this: 您可以尝试如下操作:

import shutil
from os import listdir
from os.path import isfile, join, isdir

directories = [d for d in listdir('./') if isdir(join('./', d))]

files = [f for f in listdir('./') if isfile(join('./', f)) and '.zip' in f]


# print(directories)
# print(files)

for d in directories:
    for f in files:
        if f == d + '.zip':
            shutil.rmtree(d)

Note that you need to use something like shutil.rmtree(d) if you directories contain subdirectories and/or files. 请注意,如果目录包含子目录和/或文件,则需要使用shutil.rmtree(d)类的东西。

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

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