配置文件中,文件相对路径的写法

   需要读写文件时,如果直接写绝对路径,项目移植至其他平台时,文件就会因为路径错误,读写或者导入不了,这时,我们就需要使用相对路径的写法,使项目的可移植性更好。

           相对路径的思路是:

           ① 项目内的文件路径相对项目的根目录是不变的

           ② 根目录相对平台根目录是变化的

           所以,我们只需要找到项目根目录的路径,并且与文件相对项目根目录的路径拼接一起就可以了    

           

           示例如上图所示,interface_test为项目名称,配置的文件是DirTest_Path.py,所以先根据DirTest_Path.py文件先找到interface_test项目根路径:

   代码如下:

    import  os

    #os.path.dirname(__file__)       表示当前文件父目录的路径,即如上图时,获取的路径是:"E:\python_work\test\interface_test\Utils\Dir_operate"

              #所以获取项目根目录的方法是:

               basepath=os.path.dirname(os.path.dirname(os.path.dirname(__file__) ))       #多少层父目录,包裹多少层   os.path.dirname()

               #获取结果:  basepath="E:\python_work\test\interface_test"   

              所以使用相对路径获取test_data.xlsx,可以如下拼接:

              dir_path=basepath.replace("/","\")+"\\Utils\\Dir_operate\\test_data.xlsx"                 #windows和linux系统文件的路径斜杠不一样,所以可以根据需要替换斜杠

           

       完整代码:

  import  os

  basepath=os.path.dirname(os.path.dirname(os.path.dirname(__file__) ))

  dir_path=basepath.replace("/","\")+"\\Utils\\Dir_operate\\test_data.xlsx"                #windows平台写法

   #dir_path=basepath.replace("\","/")+"//Utils//Dir_operate//test_data.xlsx"             #linux平台写法

           

猜你喜欢

转载自www.cnblogs.com/whitemouseV2-0/p/10589530.html
今日推荐