使用 pyinstaller 从 python .py 文件生成可执行文件,利用 Pandas 读取 CSV 文件?

Using pyinstaller to make an executable file from python .py file utilizing Pandas to read a CSV file?

在我的 python 文件中,“df = pd.read_csv('table.csv')”位导致 FileNotFoundError,即使它位于同一目录中。我 运行 我用 pyinstaller 构建的可执行文件。

import tkinter as tk
import pandas as pd

df = pd.read_csv('table.csv')

当我尝试使用 pyinstaller 构建 exe 时,我在终端中使用了以下代码:

pyinstaller --onefile --add-data 'table.csv:.' gui_calc.py

当我运行可执行文件...

Traceback (most recent call last):
  File "gui_calc.py", line 9, in <module>
  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 936, in __init__
  File "pandas/io/parsers.py", line 1168, in _make_engine
  File "pandas/io/parsers.py", line 1998, 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: 'table.csv'
[58900] Failed to execute script gui_calc

[Process completed] 

我的环境是:

Mac OSX 10.15.6

Python 3.7.7

pandas版本:1.1.1

zsh 5.7.1

pyinstaller 版本:4.1.dev0

基于 this answer pyinstaller 在 --onefile 模式下,每次 运行 可执行文件都会创建一个临时目录,并将其路径存储在 sys._MEIPASS 变量中。在你的代码中访问CSV文件时,需要参考这个路径。

例如(我上面提到的答案的修改代码):

import os, sys

try: # running using executable
    path = sys._MEIPASS

except: # running using .py sript
    path = os.path.abspath('.')

csv_path = os.path.join(path, 'table.csv') # valid path of the csv file

有关详细信息,请参阅:How the One-File Program Works, Defining the Extraction Location, Run-time Information