Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Tutorials listed in this section have not been reviewed nor are affliated by Code Forum. It is the sole responsbility of the authour to properly maintain and ensure information is accurate.

Python 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!
 
You can also use pathlib

Python:
from pathlib import Path

path = Path(__file__).parent

print path

# gives directory of executing script
 
Back
Top Bottom