PyInstaller cannot add .txt files

后端 未结 1 1770
不知归路
不知归路 2020-12-06 20:36

I\'m fairly new with programming (and with Python) and the Stack Overflow question/response system allowed me to resolve all my problems until now. I didn\'t find any post d

相关标签:
1条回答
  • 2020-12-06 20:39

    After the line

    a = Analysis( ... )
    

    add

    a.datas += [
        ("/absolute/path/to/some.txt","txt_files/some.txt","DATA"),
        ("/absolute/path/to/some2.txt","txt_files/some2.txt","DATA"),
        ("/absolute/path/to/some3.txt","txt_files/some3.txt","DATA"),
    ]
    

    Then in your program use the following to get the resource path of your .txt files.

    def resource_path(relative_path):
        """ Get absolute path to resource, works for dev and for PyInstaller """
        try:
            # PyInstaller creates a temp folder and stores path in _MEIPASS
            base_path = sys._MEIPASS
        except Exception:
            base_path = os.environ.get("_MEIPASS2",os.path.abspath("."))
    
        return os.path.join(base_path, relative_path)
    
     ...
    
    
     txt_data = open(resource_path("txt_files/some.txt")).read()
    

    Make sure you build it like python -m PyInstaller my_target.spec ... do not call PyInstaller directly against your .py file after you have edited your specification file or it will overwrite your edited file...

    0 讨论(0)
提交回复
热议问题