当我运行代码时,它说“TypeError: unlink() got an unexpected keyword argument 'missing_ok'”

问题描述 投票:0回答:3

这是我的代码。这是我计划中的所有内容:

from pathlib import Path
new_dir = Path.home() / "new_directory"
file_path = new_dir / "program2.py"
file_path.unlink(missing_ok=True)

文件program2.py不存在;这就是为什么我想将 missing_ok 参数设置为 True,这样它就不会引发 FileExistsError。但每次我运行代码时,它都会给我以下消息:

file_path.unlink(missing_ok=True)
TypeError: unlink() 得到了一个意外的关键字参数 'missing_ok'

我的 python 版本是否过时或我在代码中犯了错误,将不胜感激!

python filesystems
3个回答
13
投票

missing_ok
参数仅在python
Path.unlink
上添加到
3.8
。如果你想使用这个参数,你应该将 python 升级到更新的版本。

您可以使用命令查看您的python版本

python -V


3
投票

正如 napuzba 所回答的那样,

missing_ok
仅适用于 python 3.8 或更高版本。

如果你仍然必须使用python 3.7或以下,你可以这样做:

if file_path.exists():
    file_path.unlink()

如果要捕获异常:

try:
    file_path.unlink()
except FileNotFoundError:
    pass # maybe do something here

0
投票

我的问题是我使用了

os.unlink()
而不是
pathlib.Path.unlink()

© www.soinside.com 2019 - 2024. All rights reserved.