Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's os.makedirs doesn't understand "~" in my path

Tags:

python

path

People also ask

How do I get the path of a directory in Python?

To find out which directory in python you are currently in, use the getcwd() method. Cwd is for current working directory in python. This returns the path of the current python directory as a string in Python. To get it as a bytes object, we use the method getcwdb().

What does path () do in Python?

dirname(path) : It is used to return the directory name from the path given. This function returns the name from the path except the path name.


You need to expand the tilde manually:

my_dir = os.path.expanduser('~/some_dir')

The conversion of ~/some_dir to $HOME/some_dir is called tilde expansion and is a common user interface feature. The file system does not know anything about it.

In Python, this feature is implemented by os.path.expanduser:

my_dir = os.path.expanduser("~/some_dir")

That's probably because Python is not Bash and doesn't follow same conventions. You may use this:

homedir = os.path.expanduser('~')