简体   繁体   中英

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. 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 ?

i want to delete the EXTRACTED folders if they have a .zip file in the same directory.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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