首页 > 解决方案 > pyinstaller 可以制作一个动态搜索本地目录文件的可执行文件吗?

问题描述

我正在编写一个查看 config.txt 文件以搜索多个 .csv 文件名的应用程序。在我的应用程序(GUI.py + Backend.py)的本地目录中,我有以下内容:

当我使用 时pyinstaller --onedir -w --icon=email.ico GUI.py,我得到了一个适用于 Mac OS 的可执行文件,但它找不到任何我编程它在本地目录中搜索的文件。

所以,我尝试了这个:pyinstaller --onedir -w --icon=email.ico GUI.py --add-data 'config.txt' GUI.py,它最终可以识别出哪些文件丢失了:filename1.csv、filename2.csv、filename3.csv,但它们显然在我的本地目录中。最终,我想出了如何检测 filename.csv 文件,但我意识到了一些事情......

该应用程序无法再在本地搜索;它总是在查看我在--add-data. 我的目标是让客户将应用程序放在他们计算机上的任何位置,只要 filename.csv 文件与应用程序位于同一目录中,它就应该能够检测到它。是否可以制作可以在本地搜索文件的可执行python脚本?

作为记录,我的应用程序与 python 预期的所有功能完美配合,但是当我尝试使用 pyinstaller 将其转换为可执行文件时,它不再可以在本地目录中搜索 .csv 文件。

这是我的代码部分,无论如何都要进行本地搜索:

class MailChimpApp:
    # Constructor
    def __init__(self):
        arr = []
        ff = os.path.dirname(os.path.abspath(__file__)) + "/config.txt"
        for i in range(1, 5):
            line = linecache.getline(ff, i)
            index = line.find('"')
            extracted = line[index+1:-2]
            arr.append(extracted)
        self.column1 = arr[0]
        self.fname_main = arr[1]
        self.fname_Bouncer = arr[2]
        self.fname_Unsub = arr[3]
        
    def getPath(self, targetCSV):
        """
        Searches within local directory of where this python file you are reading 
        right now is located for the file(s) with 'targetCSV' string filename.
        """
        dirname = os.path.dirname(__file__)  # alternative : `os.getcwd()`
        count = -1
        fpath2 = None
        for filename in os.listdir(dirname):
            # Will NOT work with case insensitivity; use re.match() instead with regex/wild if client needs
            if filename.startswith(targetCSV) and filename.endswith(".csv"):
                count += 1
                fpath2 = filename  # takes the latest copy
        if count < 0:
            raise NoFileFound("\n" + targetCSV + " file not found.")
        elif count > 0:
            # Program cannot determine latest copy to use, so force the user to store only one copy of a file
            raise DuplicateFilesFound("\nWARNING: More than one " + targetCSV +
                                      " files were found. Please only store the latest copy in folder!")
        return fpath2

标签: pythoncsvpyinstaller

解决方案


推荐阅读