user13104924
user13104924

Reputation:

How can I change my current directory using tmpdir?

How can I write the files to the tmpdir directory instead of the current directory? How can I use tmpdir. The documentation didn't help me.

Upvotes: 2

Views: 1531

Answers (1)

Chris
Chris

Reputation: 137228

pytest recommends the newer tmp_path fixture over tmpdir. tmp_path uses pathlib, so you can conveniently use / to define paths based on them.

Here is how you might use it in a test:

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

If you really need to change to that directory, do something like

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))

but depending on the current directory is a code smell. Consider refactoring your code so it can run from anywhere.

Upvotes: 4

Related Questions