Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing relative path in Python

Tags:

python

path

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?

like image 233
Aaron Avatar asked Jun 01 '10 22:06

Aaron


People also ask

How do I read a relative path in Python?

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/ .

What is relative path in Python?

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.

How do you read a relative path?

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.


1 Answers

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.

like image 154
Dan Head Avatar answered Sep 20 '22 08:09

Dan Head