首页 > 解决方案 > Pyinstaller --add-data FileNotFoundError 同时保存数据

问题描述

我正在尝试从 python 脚本制作可执行文件,我发现PyInstaller有很多好评。

我的脚本包含一些读取 csv 文件的 pandas 指令。我尝试通过运行将文件添加到包中:

pyinstaller --add-data "data.csv:." test.py

可执行文件创建得很好,但是当我尝试打开它时,出现以下错误:

Traceback (most recent call last):
  File "test.py", line 20, in <module>
  File "test.py", line 10, in __init__
  File "test.py", line 13, in play
  File "pandas/io/parsers.py", line 686, in read_csv
  File "pandas/io/parsers.py", line 452, in _read
  File "pandas/io/parsers.py", line 946, in __init__
  File "pandas/io/parsers.py", line 1178, in _make_engine
  File "pandas/io/parsers.py", line 2008, in __init__
  File "pandas/_libs/parsers.pyx", line 382, in pandas._libs.parsers.TextReader.__cinit__
  File "pandas/_libs/parsers.pyx", line 674, in pandas._libs.parsers.TextReader._setup_parser_source
FileNotFoundError: [Errno 2] No such file or directory: 'data.csv'
[16046] Failed to execute script test
Saving session...completed.

[Process completed]

我的代码:

#!/usr/bin/env python
# coding: utf-8

import pandas as pd
import numpy as np

class MyGame():

    def __init__(self):
        self.play()

    def play(self):
        data = pd.read_csv("data.csv")
        with pd.option_context('display.max_rows', None, 'display.max_columns', None):
            print(data)
        input()


if __name__ == "__main__" : 
    MyGame()

还有我的项目文件夹

test_pyinstaller
 ├───test.py
 └───data.csv

我错过了什么?

更新:

所以我在我的代码中添加了这个命令:os.getcwd()找出脚本找不到 csv 文件的原因,结果发现工作目录是我计算机的主文件夹,而不是脚本所在的文件夹。如何更正此问题以将工作目录指向实际的脚本位置?谢谢。

标签: pythonpandaspyinstaller

解决方案


我更喜欢在基于 Linux 的操作系统上开发代码,但我发现在使用 Anaconda 的 Windows 环境中使用 auto-py-to-exe 更容易。auto-py-to-exe 也是一个 GUI 工具,可让您根据需要轻松配置 .exe 文件。它也应该在虚拟 Windows 虚拟机上工作。

链接:https ://pypi.org/project/auto-py-to-exe/


推荐阅读