问题是您甚至不检查该路径是否存在,并且您无法列出不存在的文件夹的内容。
快速示例:
>>> import os
>>> os.listdir("aaa")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'aaa'
您可以使用 os.path.isdir 检查给定路径是否存在并且是一个目录:
>>> os.path.isdir("/tmp")
True
>>> os.path.isdir("aaa")
False
(不要与 os.path.isfile 混淆 - 你想要目录,ans isfile 检查非目录文件!)
所以你的代码看起来像:
def delete_empy_folders(paths_to_folders):
for folder_path in paths_to_folders:
if os.path.isdir(folder_path) and not os.listdir(folder_path) and split(folder_path)[-1] not in ignore_list:
os.rmdir(folder_path)
Python 还有一个很好的库来处理路径,称为pathlib。如果您决定切换,可能有用的方法的快速演示:
from pathlib import Path
p = Path("/tmp")
p.is_dir() # just like os.path.isdir
p.name # to get only the last name from path, no matter how complex it is, your split(p)[-1]
p.parts # for your own split - for absolute paths first element will be "/", the rest are just stuff between '/'s
p.rmdir() # will only work if empty, just like os.rmdir
在 os/os.path 和 pathlib 中都没有现成的方法来检查目录内的文件。您使用了 os.listdir,对于 pathlib.Path 对象,我们有 iterdir,它是一个生成器(惰性,非常适合目录)——但要具有完全相同的行为,我们可以将其映射到列表:
list(p.iterdir()) # works like os.listdir(p) but returns a list of pathlib.Path objects instead of a list of str
但我们只需要知道是否至少有一个元素,所以让我们使用 next 从生成器中获取一个值——我们将使用第二个参数提供默认值,这样我们就不会得到异常:
next(p.iterdir(), None)
None 是假的(它的if check 表现得像 False/bool(None) 是 False),所以我们要么得到 Path(真)要么 None(假)。
总而言之,
def delete_empy_folders(paths_to_folders):
for folder_path in paths_to_folders:
folder_path = Path(folder_path) # if we get strings, but it would be the best to receive Path objects already
if folder_path.is_dir() and not next(folder_path.iterdir(), None) and p.name not in ignore_list:
folder_path.rmdir()