[Tutor] What is the easiest way to ensure the current working directory is the same as the directory where the main program is saved?
boB Stepp
robertvstepp at gmail.com
Fri Jun 25 20:01:22 EDT 2021
"Practical Programming -- An Introduction to Computer Science Using
Python 3.6, 3rd ed." states on p. 177: "...When you run a Python
program, the current working directory is the directory where that
program is saved..." I have established that this is not true. The
current working directory of the program depends on from what location
the program is launched. Examples:
Program: testing.py:
--------------------------
import os
print("Testing!")
print("Current working directory: ", os.getcwd())
print("Source code file: ", __file__)
Running program from different locations:
-------------------------------------------------------
PS C:\Users\boB> Practical_Programming\testing.py
Testing!
Current working directory: C:\Users\boB
Source code file: C:\Users\boB\Practical_Programming\testing.py
PS C:\Users\boB> cd c:\
PS C:\> Users\boB\Practical_Programming\testing.py
Testing!
Current working directory: C:\
Source code file: C:\Users\boB\Practical_Programming\testing.py
So this demonstrates that where you are when you launch a Python
program determines its initial working directory. A handy thing for
working in the interpreter when you want to import one of your own
programs.
Is there an _easy_ way to have a program start with its current
working directory in the same directory where its source code resides
no matter from where the program is launched? Or must I always use
the __file__ attribute to determine where the source code resides and
then change directories from there? How do people deal with their
Python applications that in theory may be installed anywhere in a
user's file system? There must be some standard way of dealing with
this that I am too dense to uncover.
TIA!
boB Stepp
More information about the Tutor
mailing list