简体   繁体   English

python os模块无法识别〜作为用户主目录的快捷方式

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

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): 我希望我的python脚本使用〜作为主目录的快捷方式更改为新目录(因此我可以在具有不同主目录名称的几台不同计算机上使用该脚本):

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

This, however generates an error. 然而,这会产生错误。 Python doesn't seem to be able to recognize ~: Python似乎无法识别〜:

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. 我在OsX Yosemite上有python 3.4。

您必须使用os.path.expanduser~扩展为实际路径:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM