OS Pythona.makedirs nie rozumie " ~ " na mojej drodze

Mam mały problem z ~ in my paths.

Ten przykład kodu tworzy kilka katalogów o nazwie "~ / some_dir " i nie rozumiem, że chciałem utworzyć some_dir w moim katalogu domowym.

my_dir = "~/some_dir"
if not os.path.exists(my_dir):
    os.makedirs(my_dir)

Zauważ, że jest to system oparty na Linuksie.

 169
Author: Peter Mortensen, 2010-01-13

3 answers

Musisz ręcznie rozwinąć tyldę:

my_dir = os.path.expanduser('~/some_dir')
 296
Author: SilentGhost,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-23 17:50:55

Konwersja ~/some_dir do $HOME/some_dir nazywa się rozszerzeniem tyldy i jest powszechną funkcją interfejsu użytkownika. System plików nic o tym nie wie.

W Pythonie ta funkcja jest zaimplementowana przez os./ align = "left" / expanduser :

my_dir = os.path.expanduser("~/some_dir")
 75
Author: ddaa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-13 14:00:40

Prawdopodobnie dlatego, że Python nie jest Bashem i nie podąża za tymi samymi konwencjami. Możesz użyć tego:

homedir = os.path.expanduser('~')
 15
Author: gruszczy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-13 13:57:01