在软件中经常需要获取文件所在路径,方法有很多种( 例如 os.path.realpath(__file__), os.getcwd(), os.path.abspath(__file__), sys.path[0], sys.argv[0]),但是各有不同,比较如下:
在一个NIPT_Analysis-V1.3.02.3.py 的程序中,编写测试代码如下,
temp_file = open("X:/WZD/temp/tempfile.txt","w")
curr_path0 = os.path.realpath(__file__)
curr_path1 = os.getcwd()
curr_path2 = os.path.abspath(__file__)
curr_path3 = sys.path[0]
curr_path4 = sys.argv[0]
path0 = os.path.dirname(curr_path0)
path1 = os.path.dirname(curr_path1)
path2 = os.path.dirname(curr_path2)
path3 = os.path.dirname(curr_path3)
path4 = os.path.dirname(curr_path4)
temp_file.write("curr_path0"+"\t"+curr_path0+"\t"+"path0"+"\t"+path0+"\n")
temp_file.write("curr_path1"+"\t"+curr_path1+"\t"+"path1"+"\t"+path1+"\n")
temp_file.write("curr_path2"+"\t"+curr_path2+"\t"+"path2"+"\t"+path2+"\n")
temp_file.write("curr_path3"+"\t"+curr_path3+"\t"+"path3"+"\t"+path3+"\n")
temp_file.write("curr_path4"+"\t"+curr_path4+"\t"+"path4"+"\t"+path4+"\n")
temp_file.close()
将该程序放置目录 X:\WZD\NIPT_Analysis_software\NIPT_Analysis-V1.3.02.3下,
然后编写.bat文件来调用NIPT_Analysis-V1.3.02.3.py 程序。将.bat文件放置在目录 X:\WZD\NIPT_Analysis_software下,
运行.bat文件,完毕后生成"X:/WZD/temp/tempfile.txt 文件,结果是:
然后用pyinstaller将 NIPT_Analysis-V1.3.02.3.py 打包成NIPT_Analysis-V1.3.02.3.exe文件,并替换.py文件,
再用.bat文件来调用NIPT_Analysis-V1.3.02.3.exe 程序。将.bat文件放置在目录 X:\WZD\NIPT_Analysis_software下,
运行结果如下:
最终选择curr_path4 = sys.argv[0]作为获取NIPT_Analysis-V1.3.02.3.py 文件路径的方法。