【问题标题】:Python3 | Pyinstaller | how do I add an excel file to the exePython3 |安装程序 |如何将excel文件添加到exe
【发布时间】:2021-12-23 05:10:48
【问题描述】:

我正在尝试从一个也使用 excel 文件的 python 脚本创建一个 exe。但是每次我运行exe时,都会出现以下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'Example.xlsx'

我真的不明白我做错了什么,希望你能帮助我。我的文件夹包含以下三个文件:

main.py
functions.py
Example.xlsx

接下来,我在终端运行 pyinstaller:

pyinstaller --onefile --add-data "Example.xlsx:." main.py

然后它会创建包含主 exe 的 dist 目录。但是当我运行它时,它给了我提到的错误。我的 main.spec 文件显示以下“数据”,我认为是正确的:

a = Analysis(...,
             datas=[('210307 Valuation portfolio (HC).xlsx', '.')],
             ...)

我在这里做错了什么?

【问题讨论】:

    标签: python excel terminal pyinstaller exe


    【解决方案1】:

    这是因为 pyinstaller 解压到一个随机的临时位置,然后运行您的文件。

    可使用sys._MEIPASS 位置访问此位置。

    几年前我遇到了一个帮助函数,它可以在开发和部署期间非常容易地确定这个位置:

    import sys, os
    
    def resource_path(relative_path):
        """ Get absolute path to resource, works for dev and for PyInstaller """
        try:
            # PyInstaller creates a temp folder and stores path in _MEIPASS
            base_path = sys._MEIPASS
        except Exception:
            base_path = os.path.abspath(".")
    
        return os.path.join(base_path, relative_path)
    

    要使用它,给函数指定文件名,它会返回一个绝对路径。

    已编辑以包含示例

    如果您当前正在使用的呼叫,例如:

    with open("Example.xlsx") as excel_file:
            do_stuff_with(excel_file)
    

    那就改用函数找位置:

    import sys, os
    
    def resource_path(relative_path):
        """ Get absolute path to resource, works for dev and for PyInstaller """
        try:
            # PyInstaller creates a temp folder and stores path in _MEIPASS
            base_path = sys._MEIPASS
        except Exception:
            base_path = os.path.abspath(".")
    
        return os.path.join(base_path, relative_path)
    
    with open(resource_path("Example.xlsx")) as excel_file:
            do_stuff_with(excel_file)
    

    【讨论】:

    • 感谢您的回答!我理解它,但真的不知道如何将它应用到我的案例中。我应该在excel文件上使用这个功能,然后按如下方式运行终端吗? "pyinstaller --onefile --add-data "Example.xlsx:resource_path(Example.xlsx)" main.py" 或者我应该如何修复它?
    • @justheretobe 这将被添加到 python 脚本中。您收到一个找不到文件的错误,因为相对路径不适用于临时 pyinstaller 位置。在您的脚本中,当您使用该文件时,您需要使用此函数来查找打包的 excel 文件的绝对路径。我无法真正提供如何在您的代码中实现它的示例,因为我不知道您如何在代码中调用它。
    • @justheretobe 我添加了我能想到的最基本的例子。
    • @justheretobe 要构建 .exe,pyinstaller --onefile --add-data="Example.xlsx" main.py 行应该可以工作。
    猜你喜欢
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多