Python Forum

Full Version: CWD (Current working directory)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

At the moment a project I am working on requires me to manually go into the first script and change the CWD to whatever the directory is of the current machine I am running the script on. Fine for me but not so good for other users whom I want to run this script on to help them automate a few processes.

Is it possible to write python code so whichever is the directory the python script is initialized in automatically becomes the current working directory?

Thanks,
phil

SO Link

I found this link but no luck yet.
I've tried this code so far:
os.chdir(os.path.dirname(sys.path[0]))
os.chdir(sys.path[0])
and I'm also trying to use these modules within python itself to change the directory and reviewing some of the docs.
So far no go.

What am I missing?
Thanks,
Phil
yes, you can use:
import os

os.chdir(os.path.dirname(__file__))
while the program is running, this will be home directory, when you exit the program, path reverts to directory at start

if you are using python 3.6 or better, you can use pathlib to control files in multiple directories, example:

from pathlib import Path
import os


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

homepath = Path('.')

rootpath = homepath / '..'

datapath = rootpath / 'data'
datapath.mkdir(exist_ok=True)  # will create directory (only if it doesn't exist, OK otherwise)

tmppath = datapath / 'tmp'
tmppath.mkdir(exist_ok=True)

mytmpfile = tmppath / 'mytmpfile.txt'

with mytmpfile.open('w') ad fp:
    fp.write('Hi, I'm a temp file\n')
os.chdir(os.path.dirname(__file__))
results in the follinging error:
[WinError 123] The filename, directory name, or volume label syntax is incorrect: ''
the file name is 'page_00_index.py'
The directory is 'D:\software\Python\python_excel\python_openpyxl_dcflog_updated-2018-11-08'

I'm trying to track down why this is now.
Thanks,
Phil
that code must be run from inside a python script.
and you must import os. Also, you may need to get absoulte path, so I modified as follows.
I also added a print of cwd.

tryme.py:
import os

os.chdir(os.path.abspath(os.path.dirname(__file__)))
print(os.getcwd())
python tryme.py
results:
Output:
(venv) larz60p@Larz60p:/.../Development/development/downloads/w-z/w/wxpython/src>
Hi Larz,

This did the trick, thank you.

I'm not exactly sure why though. I need to read up on the OS module docs, which I've not gone into in depth.

Thanks again.
Phil
if you break down:
os.chdir(os.path.abspath(os.path.dirname(__file__)))
os.chdir -- change working directory
os.path.abspath -- return absolute path
os.path.dirname -- return name portion of object.
__file__ -- The path to where the module data is stored (not set for built-in modules).