I'm writing a Python script to automate installation of UWP-Apps. The script uses Dependencies inside the script directory; my older scripts use this code:
os.chdir(os.path.dirname(sys.argv[0]))
The above code doesn't work on my current script but works fine on older scripts. It shows:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: ''
Researching this topic, I only found talk about running the script from outer/different 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.
.py file from where it is:cd path/to/python/file && python ../.py
Save this as runPython.sh in the directory where you're running the python script from, is:
#!/bin/sh
cd path/to/python/file
python ../script.py
Make it executable (for yourself):
chmod +x ./runPython.sh
Then you can simply enter your directory and run it:
./runPython.sh
mydir = os.getcwd() # would be the folder where you're running the file
mydir_tmp = "path/to/python/file" # get the path
mydir_new = os.chdir(mydir_tmp) # change the current working directory
mydir = os.getcwd()
The reason you got an error was because sys.argv[0] is the name of the file itself, instead you can pass the directory as a string and use sys.argv[1] instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With