Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python os module does not recognize ~ as shortcut for the user home directory

Tags:

python

macos

I want my python script to change to a new directory using ~ as a shortcut for the home directory (so I can use the script on several different computers with different home directory names):

os.chdir('~/google_drive/2014-11-05-QiimeAnalysis/quality_filtering/)

This, however generates an error. Python doesn't seem to be able to recognize ~:

FileNotFoundError: [Errno 2] No such file or directory: '~/google_drive/2014-11-05-QiimeAnalysis/quality_filtering/'

Why does this happen and is there a way around it? I have python 3.4 on OsX Yosemite.

like image 242
Drosophila Avatar asked Nov 10 '14 19:11

Drosophila


People also ask

How do I reference the home directory in Python?

path. expanduser('~') to get the home directory in Python. This also works if it is a part of a longer path like ~/Documents/my_folder/. If there is no ~ in the path, the function will return the path unchanged.

How do you call a directory in Python?

getcwd method we used in Python to get the current directory, we use the chdir() methods in the os module to change the current directory. The current directory is changed to retrieve files or run scripts that are present in other directories.

How do I nest a directory in Python?

For python 3.2 and above, you can use os. makedirs . Using method makedirs() from module os , a nested directory can be created in a simple way. The parameter passed is the nested directory we wanted to create.


1 Answers

You have to use os.path.expanduser to expand the ~ into an actual path:

os.chdir(os.path.expanduser('~/google_drive/2014-11-05-QiimeAnalysis/quality_filtering/'))
like image 108
Daniel Roseman Avatar answered Nov 07 '22 14:11

Daniel Roseman