Search code examples
pythondirectoryexecutabledirectory-structure

Setting Folder Path for Executable


I have written a script that takes CSV files as input, edits them and saves them to a folder. Everything works well when running in IDE (Pycharm) but when I run the executable (generated using Pyinstaller) the script crashes as it doesn't find the folders with the CSV files. If manually go to the directory in terminal and run the executable the program works as it should, but doesn't if you run it by double clicking the icon.

The folder structure is as follows:

Editor ( main folder)
-> Input1 (folder)
                 |-> contains CSV files to edit
-> Input2 (Folder) 
                 |-> contains CSV files to edit
-> Output (folder) 
                 |-> edited CSV should go here
-> Main (executable)

I have tried using

path = (sys.path[0])
path = os.path.dirname(os.path.abspath(__file__))
path = os.getcwd()

When I print path, Using IDE i get the path for where my program is stored. But once I create an executable the printed path does not match where the executable is running from, it gives root/user/

I would like to be able to run the executable from any location on the computer, as long as the input and output folder are in the same directory

How would I go about fixing this problem? I'm running MAC OS X Catalina, Python 3.7


Solution

  • I was able to solve the problem by using the following code:

    path = os.path.dirname(sys.argv[0])
    

    Then was able to check if csv files exist using the following:

    checkpath =  os.path.join(path, "Folder_Name")
    
    if not any(os.path.splitext(f)[1] == '.csv' for f in os.listdir(checkpath)):
        print("Folder is empty, Please check Folder contains CSV files")
        print("Press Any key to Return to Main Menu")
        input()
        main()
    else:
        print("\nStarting Data Editing")