Pro*_*mer 5 python macos locked-files python-3.x
在我的脚本的主要目的完成后,作为"清理",调用一个函数来递归查看每个文件夹并删除以预定的一组扩展名结尾的所有文件.
我在测试期间,发现一些文件扩展名在删除列表中的文件实际上会抛出一个错误:[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')
Run Code Online (Sandbox Code Playgroud)
如果有人能告诉我如何将这些功能集成到子程序中,我将非常感激.干杯.
编辑:根据请求删除错误处理
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))
Run Code Online (Sandbox Code Playgroud)
您可以使用以下命令解锁该文件chflags:
os.system('chflags nouchg {}'.format(filename))
Run Code Online (Sandbox Code Playgroud)
(有一个函数os.chflags,但是与锁定状态相关的标志不是常规的,而是os模块文档中所说的“用户定义”标志,正如您通过查看 可以看到的那样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:
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1290 次 |
| 最近记录: |