Problem:
Recently in the study of import, found not like import xxx, or from xxx import ooo
So simple. For example, look at the following diagram:
Do you want to import to call pre.tab.py in te.py??
Direct import:
Import Pre_tab
Traceback (most recent): File "c:/users/administrator/pycharmprojects/laonanhai/shop_store/test/te.py ", line +, in <module> import pre_tabimporterror:no module named ' Pre_tab '
Knowledge Points:
By watching the video, I learned the following two points:
1. Os.path.abspath (__file__) returns the absolute path of the current file
Under the te.py file:
Import OSX = Os.path.abspath (__file__) print (x)
Output:
View Code
2.os.path.dirname () returns the previous layer path of the current file
Under the te.py file:
X1 = Os.path.dirname (os.path.dirname (x)) print (x1) sys.path.append (x1) Print (Sys.path
Output:
View Code
Finally, you can see through print (Sys.path) that
C:\Users\Administrator\PycharmProjects\laonanhai\shop_store path has been added to Sys.path
Extra Harvest
Under the pre_tab.py file:
"" "C:\Users\Administrator\PycharmProjects\laonanhai\shop_store\pre_tab.py" "" Print ("AA")
Unexpectedly, the exposure of the wrong!!!
SyntaxError: (Unicode error) ' Unicodeescape ' codec can ' t decode bytes in position 3-4: truncated \uxxxxxxxx escape
Later, reference
http://blog.csdn.net/wlsyn/article/details/49613867 Original is the file path, the backslash \u the error, after the backslash and add a backslash escaped on the line, after testing, the code after the comment does not error, remove the comments, can also read and write files normally
Essay supplement: About __IMPORT__
obj = __import__ ("Lib.manager") print (obj) #没有导入manager. Py#<module ' lib ' from ' c:\\users\\administrator\\ pycharmprojects\\laonanhai\\day6_test\\lib\\__init__.py ' >obj.order () #AttributeError: ' Module ' object has No attribute ' order '
Obj1 = __import__ ("Lib.manager", Fromlist=true) #表示按路径连接方式导入print (obj1) #导入manager #<module ' Lib.manager ' From ' c:\\users\\administrator\\pycharmprojects\\laonanhai\\day6_test\\lib\\manager.py ' >obj1.order () # successful execution of the order () method for manager.py under Lib
Source: Http://www.cnblogs.com/0zcL
Python path Import