python 软件目录结构规范
按标准执行文件、配置文件、程序文件是不在一个文件夹下的。
查看文件的当前路径,
1.使用第三方平台执行:print __file__ 输出D:\soft\eclipse-workspace\ceshi\lianx1.py 输出的看着是绝对路径其实是一个相对路径。
在dos模式下可以直接看出是相对路径:
2.通过执行:print os.path.abspath(__file__) 可以输出当前文件的绝对路径
当执行文件和程序文件不在一个文件夹下时,如何通过执行执行文件运行不同文件夹下的程序文件呢,需要:os.path.dirname()方法。
os.path.dirname()取当前文件的路径,不要文件名,具有返回上一级的功能。
import os print os.path.dirname(os.path.abspath(__file__)) >>D:\soft\eclipse-workspace\ceshi
再返回上一级,
import os print os.path.dirname(os.path.dirname(os.path.abspath(__file__))) >>D:\soft\eclipse-workspace
实例,如:
通过执行atm.py文件使执行main.py文件中的程序,需要在atm.py文件中做以下操作。
import os dir=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(dir) from core import main #注core 文件里一定要有__init__.py这个文件,不然在引用这个包的文件里提示找不到该模块 main.log()
本博客只记录个人的学习过程,如对文中有不懂的地方,可以在评论区留言!