简体   繁体   中英

Python import from a different directory using “~” symbol

Under a linux structure, i've noticed that the following works:

import sys
sys.path.append("/home/username/fullpathname/")
import my_module

however the following does not

import sys
sys.path.append("~/fullpathname")
import my_module

is there a way to use the "~" operator? I don't understand why python wants the full directory. Thank you!

You can use os.path.expanduser :

import sys, os
sys.path.append(os.path.expanduser("~/fullpathname"))
import mymodule

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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