I'm running a Mac OS X environment and am used to using ~/ to provide the access to the current user's directory.
For example, in my python script I'm just trying to use
os.chdir("/Users/aaron/Desktop/testdir/")
But would like to use
os.chdir("~/Desktop/testdir/")
I'm getting a no such file or directory error when trying to run this. Any ideas?
First, you have to import the os module in Python so you can run operating system functionalities in your code. Then you create the variable absolute_path which fetches the current directory relative to the root folder. This is the full path to your working directory, in this case, ~/home/projects/example-project/ .
A relative file path is interpreted from the perspective your current working directory. If you use a relative file path from the wrong directory, then the path will refer to a different file than you intend, or it will refer to no file at all.
A relative path refers to a location that is relative to a current directory. Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy.
You'll need to use os.path.expanduser(path)
os.chdir("~/Desktop/testdir/")
is looking for a directory named "~" in the current working directory.
Also pay attention to the documentation of that function - specifically that you'll need the $HOME
environment variable set properly to ensure that the expansion takes place. Most of the time this wont be a problem but if the expansion doesn't take place, that's the likely reason.
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