首页 文章

如何使用Python解锁锁定的文件和文件夹(mac)

提问于
浏览
5

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

我在测试期间,发现一些文件扩展名在要删除的列表中的文件实际上会抛出一个错误: [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))

1 回答

  • 2

    您可以使用 chflags 命令解锁文件:

    os.system('chflags nouchg {}'.format(filename))
    

    (有一个函数 os.chflags ,但与锁定状态关联的标志不是常规标志,而是os module documentation调用"user-defined"标志,正如您可以通过查看 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:
        ...
    

相关问题