如何使用tmpdir更改当前目录



如何将文件写入tmpdir目录而不是当前目录?如何使用tmpdir。文件对我没有帮助。

pytest建议使用较新的tmp_path夹具而不是tmpdirtmp_path使用pathlib,因此可以方便地使用/基于它们定义路径。

以下是如何在测试中使用它:

def test_foo(tmp_path):
make_file(tmp_path / "file1", "something")

如果确实需要更改到该目录,请执行类似的操作

def test_foo(tmp_path):
os.chdir(tmp_path)  # If you're using Python 3.6 or later
# or if you're on an older version:
os.chdir(str(tmp_path))

但取决于当前目录是一种代码气味。考虑重构代码,使其可以在任何地方运行。

最新更新