【问题标题】:Using pyinstaller to make an executable file from python .py file utilizing Pandas to read a CSV file?使用 pyinstaller 从 python .py 文件制作可执行文件,利用 Pandas 读取 CSV 文件?
【发布时间】:2021-02-02 06:37:10
【问题描述】:

在我的 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

熊猫版本:1.1.1

zsh 5.7.1

pyinstaller 版本:4.1.dev0

【问题讨论】:

  • 你是不是把dist文件夹里的exe复制到项目目录下?我不认为--add-data 'table.csv:.' 这实际上允许您将 csv 存储在
  • 这成功了!但只有当我通过终端在文件目录中输入./gui_calc 执行文件时

标签: python pandas csv tkinter pyinstaller


【解决方案1】:

基于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 WorksDefining the Extraction LocationRun-time Information

【讨论】:

  • 感谢这工作!更好的是,当我将代码发送给其他用户时,它使我的代码具有可移植性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-22
  • 1970-01-01
  • 1970-01-01
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 2022-09-23
相关资源
最近更新 更多