简体   繁体   中英

Function that takes folder name as argument (python)

I am trying to write a function that deleting all directories and files except the one (folder_to_exclude)

def cleanDir(self,dirpath, folder_to_exclude, handler):     
    for root, dirs, files in walk(dirpath, topdown=True):
        for file_ in files:
            full_path = path.join(root, file_)
            if folder_to_exclude not in full_path:
                rmtree(full_path, onerror = handler)
        for folder in dirs:
            full_path = path.join(root, folder)
            if folder_to_exclude not in full_path:
                print("cleanDir  full_path  : ",full_path)
                rmtree(full_path, onerror = handler)

I am calling this function from another part of my code, using:

self.cleanDir(self.work_dir, self.script_dir, myHandler)

Where:

  • self.work_dir: is the working directory
  • self.script_dir: is the directory to exclude
  • myHandler: a handler for exception (not important in my case)

My question is: When I print the directories that I will delete using the line in the cleanDir function, I find that I am printing the folder_to_exclude too, and then I am deleting it.

I don't understand why !

Maybe values are not the same.

You could check

print( folder_to_exclude not in full_path )

print( folder_to_exclude == full_path )

print( len(folder_to_exclude) == len(full_path) )

Maybe one of them has spaces or tabs at the end and you can't see it.

You may check if it is the same when you try to remove spaces and tabs

print( folder_to_exclude.strip() == folder_to_exclude )
print( full_path.strip() == full_path )

print( folder_to_exclude.strip() == full_path.strip() )

OR maybe you use some chars which can look similar but they have different codes.

You can use for -loop to compare char-by-char

for a, b in zip(folder_to_exclude, full_path): 
    print( a, b, a == b, ord(a), ord(b) )

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