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