klaus
klaus

Reputation: 1227

Is it a good practice to use os.chdir(os.path.dirname(__file__)) at the beginning of the file?

I have a script that loads a lot of files in its directory, and this script could be called from any location. I want to know if it is ok to use os.chdir(os.path.dirname(__file__)) at the beginning of the file to make things less verbose.

Directory of the script:

script/path/
  do_stuff.py
  src/
    ..some files

The script is called like that:

$ python3 script/path/do_stuff.py

So, instead of doing

with open(os.path.join(os.path.dirname(__file__), 'src/..')) as f:
    ...

I add os.chdir(os.path.dirname(__file__)) after the imports and do:

with open('src/..') as f:
    ...

Is this considered a good practice? Or should I avoid it in order to avoid complications in more complex projects?

Upvotes: 2

Views: 1811

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545943

Another alternative:

  1. Write a function that gives you the correct path for a local file resource:

    def get_resource_file(path):
        return os.path.join(os.path.dirname(__file__), path)
    

    And then:

    with open(get_resource_file('src/…')):
        …
    

As mentioned in my comment, changing the current working directory means you can no longer accept relative paths from user input (unless you first store the original working directory and construct absolute paths from that). This is probably the most common scenario of a command line tool:

path/to/tool local/path/to/file

By contrast, the gain of cd’ing away from the user’s working directory is relatively small.

Upvotes: 6

Related Questions