python文件解除占用_如何使用Python解锁锁定的文件和文件夹(mac)
在我的腳本的主要目的完成后,作為“清理”,調用一個函數來遞歸查看每個文件夾并刪除以預定的一組擴展名結尾的所有文件.
我在測試期間發現一些文件擴展名在刪除列表中的文件實際上會拋出一個錯誤:[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))
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的python文件解除占用_如何使用Python解锁锁定的文件和文件夹(mac)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 输出引号_python输出
- 下一篇: react实战项目_React实战之Re