Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
Resource icon

Python - Path to working directory and files.

To create a portable application or script, the first step is to set a universal method so the working directory will always find its dependent files. And the most dependable way is to utilize the standard libraries that Python comes with, in this case, "sys" and "os".

To avoid the program changing location on the stored computer always include:
Python:
import sys, os
LOCAL_DIR_PATH = os.path.dirname(sys.argv[0])
LOCAL_DIR_PATH will always have the correct path, in a string format, to the working directory,

If you want to call or include another file in you program always use join:
Python:
FILE_PATH = os.path.join(LOCAL_DIR_PATH, FILE_NAME)
FILE_NAME in this case, a local file, is stored in the same folder.

If the file is stored in a sub-directory within the working folder, define the folder first before addressing the file.
Python:
FOLDER_PATH = os.path.join(LOCAL_DIR_PATH, FOLDER_NAME)
FILE_PATH = os.path.join(FOLDER_PATH, FILE_NAME)

Avoid using a full path in a pure string variable
Python:
WORKING_DIR_PATH = "C:\dev\python\project"
This makes the script non-shareable since other users might store it on a different path.

Note: "os" is a standard library, meaning it comes with Python and is cross-platform. After os has been first imported, there is no loss in performance to repeatedly call upon os built-in modules, for instance:
Python:
os.path
So there should be no reason not to use os!
Author
Nidas
Views
427
First release
Last update

Ratings

0.00 star(s) 0 ratings
Back
Top Bottom