在我的脚本的主要目的完成后,作为“清理”,调用一个函数来递归查看每个文件夹并删除以预定的一组扩展名结尾的所有文件.
我在测试期间发现一些文件扩展名在删除列表中的文件实际上会抛出一个错误:[Errno 1]不允许操作:’/ location / of / locked / file.png.查看文件本身,它似乎是锁定(在Mac上).
>如何使用Python从每个文件/文件夹中删除锁定的属性(如果存在),然后删除文件,如果它在扩展名中结束?
优选地,这可以在下面的相同功能中完成,因为遍历输入目录需要很长时间 – 只需处理一次即可.
>这如何影响Windows上脚本的完整性?
我已经开始对它进行编程,使其在操作系统之间兼容,但是(据我所知),Windows上不存在锁定属性,就像它在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))