'Python: how to include data files in pyinstaller?

I'm trying to create an executable of a project with the following structure

/projectdir
    project.spec
    /src
        /project
            main.py
            /submodule1
                 f1.py
            /res
                 f2.csv

Inside of f1.py there is a call to read f2.csv with the form open('src/project/res/f2.csv'). When I package it with build and install it somewhere else, it works without problems. However, I'm not able to create a working executable with pyinstaller (pyinstaller -F project.spec).

I've tried adding the file with datas inside of project.spec, as explained in the documentation of pyinstaller:

 a = Analysis(['src/project/main.py'],
             pathex=[os.getcwd()+'/venv/lib/python3.8/',
                     os.getcwd()+'/src/'],
             binaries=[],
             datas=[('./src/project/res/f2.csv',
                     '/src/project/res/')],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=['tkinter'],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)

However, when I execute the generated executable with pyinstaller I get an file not found error:

FileNotFoundError: [Errno 2] No such file or directory: 'src/project/res/f2.csv'

What is the correct syntax to access this file? Should I change something in the *.spec file or should the call from f1.py be changed?

Many thanks



Solution 1:[1]

I had the same problem with pyinstaller. I used a workaround hack that worked for me for image and .mo files. I created a script that turned the data files into base64. This same script then wrote out another python file containing the base64. This file was then packaged with pyinstaller. You can then write the file out for use in your software. Example below shows both the creator file and the output file. At the end of the main.py file (in the qualcoder folder), I write the data files back out to be used.

https://github.com/ccbogel/QualCoder/tree/master/qualcoder/locale

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Colin Curtain