Python: Change the Scripts Working Directory to the Script's Own Directory

python: Change the scripts working directory to the script's own directory

This will change your current working directory to so that opening relative paths will work:

import os
os.chdir("/home/udi/foo")

However, you asked how to change into whatever directory your Python script is located, even if you don't know what directory that will be when you're writing your script. To do this, you can use the os.path functions:

import os

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)

This takes the filename of your script, converts it to an absolute path, then extracts the directory of that path, then changes into that directory.

Change directory to the directory of a Python script

os.chdir(os.path.dirname(__file__))

Run Python Script From Script Directory/Current Directory

import os
from os.path import abspath, dirname
os.chdir(dirname(abspath(__file__)))

You can use dirname(abspath(__file__))) to get the parent directory of the python script and os.chdir into it to make the script run in the directory where it is located.

Change working directory when calling another script in Python

You identified the problem correctly but you are searching for the wrong answer. In most cases it is not a good idea to fiddle around with the working directory. If this is done at multiple occasions, you might end up in a place you did not expect.

You run into your problem because your script failed to find a file. This is because you hard-coded the path to it. Something like

with open('stat_tier_list.txt', 'r') as f:

can hardly be good idea. Use

path_to_file = 'stat_tier_list.txt'
with open(path_to_file , 'r') as f:

instead. This way you can make the path an argument of your function

# read_a_file.py
def read_file(path_to_file):
with open(path_to_file, 'r') as f:

Now, go back to base.py and call the function properly:

# base.py
from pathlib import Path
from read_a_file import read_file # You may have to reorganise your folder structure to make this work

PATH_ROOT = Path('C:\Users\agctute\PycharmProjects\sapaigenealg')

path_to_file = PATH_ROOT.joinpath('file_to_be_read.txt')

read_a_file(path_to_file)

I suppose, that is what you really want. A function read_a_file should always accept an argument which specifies what file has to be read.

How to change working directory of Python script during execution?

There is return statement before os.chdir, so that line is not executed.



Related Topics



Leave a reply



Submit