I'm trying to make an executable from a python script, and I found many good reviews of PyInstaller.
My script contains some pandas instruction to read a csv file. I tried adding the file to the bundle by running:
pyinstaller --add-data "data.csv:." test.py
The executable is created fine but when I try to open it, I get the following error:
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]
My code:
#!/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()
And my project folder
test_pyinstaller
├───test.py
└───data.csv
What am I missing?
So I added this command in my code: os.getcwd()
to find out why the script couldn't find the csv file and it turns out the working directory was the home folder of my computer and not the one where the script was located. How do I correct this to point the working directory to the actual script location? Thanks.
I found a solution thanks to this other post on StackOverflow: Determining application path in a Python EXE generated by pyInstaller
#!/usr/bin/env python
# coding: utf-8
import pandas as pd
import numpy as np
import os
import sys
class MyGame():
def __init__(self):
# get script directory where also the csv file is.
if getattr(sys, 'frozen', False):
application_path = sys._MEIPASS
else:
application_path = os.path.dirname(os.path.abspath(__file__))
self.path = application_path
self.play()
def play(self):
print(self.path)
print(self.path + "/data.csv")
data = pd.read_csv(self.path + "/data.csv")
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
print(data)
input()
if __name__ == "__main__" :
MyGame()