有些脚本结尾就是想顺手清一个临时文件,没了也别炸。
环境:Python 3.10+,只用标准库。
from contextlib import suppress
from pathlib import Path
p = Path('tmp-result.txt')
p.write_text('done', encoding='utf-8')
with suppress(FileNotFoundError):
p.unlink()
print('cleaned')
比外面套一层 try/except 看着轻一点,写小脚本时挺舒服的。