python文件解除占用_如何使用Python解锁锁定的文件和文件夹(mac)
在我的腳本的主要目的完成后,作為“清理”,調(diào)用一個(gè)函數(shù)來(lái)遞歸查看每個(gè)文件夾并刪除以預(yù)定的一組擴(kuò)展名結(jié)尾的所有文件.
我在測(cè)試期間發(fā)現(xiàn)一些文件擴(kuò)展名在刪除列表中的文件實(shí)際上會(huì)拋出一個(gè)錯(cuò)誤:[Errno 1]不允許操作:’/ location / of / locked / file.png.查看文件本身,它似乎是鎖定(在Mac上).
>如何使用Python從每個(gè)文件/文件夾中刪除鎖定的屬性(如果存在),然后刪除文件,如果它在擴(kuò)展名中結(jié)束?
優(yōu)選地,這可以在下面的相同功能中完成,因?yàn)楸闅v輸入目錄需要很長(zhǎng)時(shí)間 – 只需處理一次即可.
>這如何影響Windows上腳本的完整性?
我已經(jīng)開(kāi)始對(duì)它進(jìn)行編程,使其在操作系統(tǒng)之間兼容,但是(據(jù)我所知),Windows上不存在鎖定屬性,就像它在mac上一樣,并且可能導(dǎo)致未知的副作用.
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')
如果有人能告訴我如何將這些功能集成到子程序中,我將非常感激.干杯.
編輯:根據(jù)請(qǐng)求刪除錯(cuò)誤處理
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))
超強(qiáng)干貨來(lái)襲 云風(fēng)專訪:近40年碼齡,通宵達(dá)旦的技術(shù)人生總結(jié)
以上是生活随笔為你收集整理的python文件解除占用_如何使用Python解锁锁定的文件和文件夹(mac)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python 输出引号_python输出
- 下一篇: python批处理文件_Python文件