[Python] How to incorporate a csv into an exe file in python?

Discussão em 'Python' iniciado por Stack, Abril 10, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to incorporate a csv into the executable file in python, so that the csv is not necessary for the exe to work. I tried two methods, both fail (exe works only when csv is present in the folder).

    First method is cd_Freeze (python setup.py build). My setup code is:

    from cx_Freeze import setup, Executable

    # Define build options, including the CSV file
    build_exe_options = {
    "include_files": ["csv_text.csv"], # Ensure this file is bundled with the executable
    "build_exe": "dist" # Specify the output directory
    }

    # Setup configuration
    setup(
    name="IncludeCSVApp",
    version="1.0",
    description="Application with an embedded CSV file",
    options={"build_exe": build_exe_options},
    executables=[Executable("include_csv.py", base=None)] # Base can be set to
    'Win32GUI' for GUI apps
    )


    and the lines for finding the path of the csv file in the main.py are: def resource_path(relative_path):

    def resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
    print(f"_MEIPASS directory: {sys._MEIPASS}") # Debugging output
    csv_file_path = os.path.join(sys._MEIPASS, 'csv_text.csv')
    else:
    csv_file_path = os.path.join(os.path.abspath("."), 'csv_text.csv')
    return os.path.join(os.path.abspath("."), relative_path)

    # Check if file exists
    csv_file_path = resource_path('csv_text.csv')


    This method by the way does not produce the build folder, but only when I am trying to incorporate the csv file, if this makes any difference.

    Second, I tried the command: pyinstaller --onefile --add-data "csv_text.csv;data" your_script.py

    Any ideas?

    Continue reading...

Compartilhe esta Página