java如何解除文件锁定状态_如何使用Python解锁锁定的文件和文件夹(mac)

在我的脚本的主要目的完成后,作为“清理”,调用一个函数来递归查看每个文件夹并删除以预定的一组扩展名结尾的所有文件 .

我在测试期间,发现一些文件扩展名在要删除的列表中的文件实际上会抛出一个错误: [Errno 1] Operation not permitted: '/location/of/locked/file.png . 查看文件本身,它似乎是锁定(在Mac上) .

How would I go about removing the locked attribute (should it exist) from every file/folder using Python, then delete the file if it ends in the extension?

优选地,这可以在下面的相同功能中完成,因为遍历输入目录需要很长时间 - 只需处理一次即可 .

How does this affect the script's integrity on 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')

如果有人能告诉我如何将这些功能集成到子程序中,我将非常感激 . 干杯 .

EDIT: 根据请求删除了错误处理

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值