Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

python - PyInstaller cannot add .txt files

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 directly addressing my current issue, but have to admit that I don't really know what's wrong. Let me explain.

I'm trying to make an executable file of a *.py script using PyInstaller. There's no problem doing it with a simple Python script (using --onefile), but it does not work when it comes to a more complex program that uses other *.py and *.txt files. I know that I need to modify the specification file and tried many alternatives - adding hidden files for instance.

Here are the files:

  • UpdatingStrategy.py (the target file to transform in executable)
  • LPRfunctions.py (UpdatingStrategy.py imports functions from this file)

The following *.txt files are read by UpdatingStrategy.py:

  • Strategy_Observ.txt
  • Strategy_Problems.txt
  • Updating_Observ1.txt
  • Updating_Observ2.txt
  • Updating_Problems.txt

I'm using Python 3.5 and Windows 10. Tell me if you need extra information.

How do I use the specification file properly and modify it in order to make an executable file of UpdatingStrategy.py?

I have read the PyInstaller documentation, but I lack many key principles and I couldn't make it work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...