问题:
最近在学习import的时候,发现不像import xxx,或者from xxx import ooo
这样简单。比如,看下面这个图:
要导入才能在te.py调用pre.tab.py??
直接导入:
import pre_tab
Traceback (most recent call last):
File "C:/Users/Administrator/PycharmProjects/laonanhai/shop_store/test/te.py", line 14, in <module>
import pre_tab
ImportError: No module named 'pre_tab'
知识点:
通过看视频,学到了下面两点:
1. os.path.abspath(__file__) 返回当前文件的绝对路径
在te.py文件下:
import os
x = os.path.abspath(__file__)
print(x)
输出:
C:\Python34\python3.exe C:/Users/Administrator/PycharmProjects/laonanhai/shop_store/test/te.py
C:\Users\Administrator\PycharmProjects\laonanhai\shop_store\test\te.py Process finished with exit code 0
2.os.path.dirname() 返回当前文件的上一层路径
在te.py文件下:
x1 = os.path.dirname(os.path.dirname(x))
print(x1)
sys.path.append(x1) print(sys.path
输出:
C:\Python34\python3.exe C:/Users/Administrator/PycharmProjects/laonanhai/shop_store/test/te.py
C:\Users\Administrator\PycharmProjects\laonanhai\shop_store\test\te.py
C:\Users\Administrator\PycharmProjects\laonanhai\shop_store
['C:\\Users\\Administrator\\PycharmProjects\\laonanhai\\shop_store\\test', 'C:\\Python34\\lib\\site-packages\\pip-8.1.2-py3.4.egg', 'C:\\Users\\Administrator\\PycharmProjects\\laonanhai', 'C:\\Windows\\SYSTEM32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages', 'C:\\Users\\Administrator\\PycharmProjects\\laonanhai\\shop_store']
最后,通过print(sys.path)可以看到,
C:\Users\Administrator\PycharmProjects\laonanhai\shop_store路径已经加入sys.path
额外收获 在pre_tab.py文件下:
"""
C:\Users\Administrator\PycharmProjects\laonanhai\shop_store\pre_tab.py
"""
print("AA")
竟然,曝错了!!!
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 3-4: truncated \UXXXXXXXX escape
后来参考了
http://blog.csdn.net/wlsyn/article/details/49613867原来是文件路径中,反斜杠 \u 报的错,在反斜杠后面再加一个反斜杠转义了就行了,经测试,注释后的代码不报错,去掉注释,也能正常读写文件 随笔补充:关于__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() #成功执行lib下的manager.py的order()方法
出处:http://www.cnblogs.com/0zcl