作为"清理"在我的脚本的主要目的完成之后,调用一个函数来递归查看每个文件夹并删除以预定的一组扩展名结尾的所有文件。
在测试过程中,我发现一些文件扩展名在要删除的文件列表中实际上会抛出一个错误:[Errno 1] Operation not permitted: '/location/of/locked/file.png
。查看文件本身,它似乎是已锁定(在Mac上)。
REMOVE_FILETYPES = ('.png', '.jpg', '.jpeg', '.pdf')
def cleaner(currentPath):
if not os.path.isdir(currentPath):
if currentPath.endswith(REMOVE_FILETYPES) or os.path.basename(currentPath).startswith('.'):
try:
os.remove(currentPath)
print('REMOVED: \"{removed}\"'.format(removed = currentPath))
except BaseException as e:
print('ERROR: Could not remove: \"{failed}\"'.format(failed = str(e)))
finally:
return True
return False
if all([cleaner(os.path.join(currentPath, file)) for file in os.listdir(currentPath)]):
try:
os.rmdir(currentPath)
print('REMOVED: \"{removed}\"'.format(removed = currentPath))
except:
print('ERROR: Could not remove: \"{failed}\"'.format(failed = currentPath))
finally:
return True
return False
cleaner(r'/path/to/parent/dir')
如果有人能告诉我如何将这些功能集成到子程序中,我真的很感激。欢呼声。
编辑:根据请求删除了错误处理
def cleaner(currentPath):
if sys.platform == 'darwin':
os.system('chflags nouchg {}'.format(currentPath))
if not os.path.isdir(currentPath):
if currentPath.endswith(REMOVE_FILETYPES) or os.path.basename(currentPath).startswith('.'):
try:
os.remove(currentPath)
print('REMOVED: \"{removed}\"'.format(removed=currentPath))
except PermissionError:
if sys.platform == 'darwin':
os.system('chflags nouchg {}'.format(currentPath))
os.remove(currentPath)
if all([cleaner(os.path.join(currentPath, file)) for file in os.listdir(currentPath)]) and not currentPath == SOURCE_DIR:
os.rmdir(currentPath)
print('REMOVED: \"{removed}\"'.format(removed=currentPath))
答案 0 :(得分:2)
您可以使用chflags
命令解锁文件:
os.system('chflags nouchg {}'.format(filename))
(有一个函数os.chflags
,但与锁定状态关联的标志不是常规标志,而是os
module documentation调用“用户定义”标志的内容,如您所见看着os.stat(locked_filename).st_flags
。)
要解决您的问题,我将上面的chflags
命令添加到特定的except:
,以查找您尝试删除锁定文件的错误以及平台检查:
try:
os.remove(currentPath)
print('REMOVED: \"{removed}\"'.format(removed = currentPath))
except PermissionError:
if sys.platform == 'darwin':
os.system('chflags nouchg {}'.format(currentPath))
os.remove(currentPath)
else:
raise
except BaseException as e:
...