这里写自定义目录标题
最近在用python打包exe项目,在运行exe文件后出现加载配置文件路径不对的问题。 主要原因是利用os.path.dirname(_file_)加载相对路径文件的时候,os.path.dirname(_file_)只是代码的路径,不是生成exe文件之后#运行exe文件的所在路径。因此会出现下面的报错:
No such file or directory: 'C:\Users\qhcsu\AppData\Local\Temp\_MExx\xx\xx错误
正确的需要用下面这种方式获取配置文件的路径
def get_config_file_path():
# 获取exe文件所在的目录
exe_dir = os.path.dirname(sys.argv[0])
# 组合配置文件的路径
config_file_path = os.path.join(exe_dir, 'config.txt')
return config_file_path
完整的例子:
import os
import sys
def get_config_file_path():
# 获取exe文件所在的目录
exe_dir = os.path.dirname(sys.argv[0])
# 组合配置文件的路径
config_file_path = os.path.join(exe_dir, 'config.txt')
return config_file_path
def load_config():
config_file_path = get_config_file_path()
with open(config_file_path, 'r') as config_file:
config_data = config_file.read()
# 在这里可以进行配置文件的处理,例如解析配置数据等
return config_data
if __name__ == "__main__":
config_data = load_config()
print("配置文件内容:")
print(config_data)
在这个修改后的代码中,我们通过sys.argv[0]获取了打包后的exe文件的绝对路径,并使用os.path.dirname()获取该exe文件所在的目录。然后我们使用该目录来拼接配置文件的路径,确保可以正确加载配置文件。
使用更新后的代码重新运行 pyinstaller 命令,并确保 config.txt 与生成的 script.exe 位于同一目录下。然后再次运行 script.exe,应该可以正确加载配置文件,不再出现找不到文件的错误。