Reputation: 15
I made a script that when clicked on it copies all the files of the directory where it was opened in on to a USB. It works inside Pycharm but when I convert it to an executable (When I use pyinstaller to convert the .py to a .exec) it does not work. I’m almost certain I know what’s wrong but I don’t know how to fix it.
import shutil
import os
current = os.getcwd()
list_of_files = os.listdir(current)
def get_files():
print('CURRENT: ' + current)
print('File_List: ' + str(list_of_files))
for files in list_of_files:
shutil.copy(current + '/' + files, '/Volumes/U/Copy_things')
get_files()
Long story short I’m using os.getcwd() so the file knows where it is located.
When I execute the file in Pycharm the current directory that os.getcwd() gives me is
CURRENT: /Users/MainFrame/Desktop/python_test_hub/move_file_test
But when I open the executable (same folder as the .py file ) and the terminal opens up os.getcwd() gives me is
CURRENT: /Users/MainFrame
So I need to find a way for the executable to open up the terminal where it is located so it can copy those files. I want to be able to execute it from any folder and copy the files to a USB.
Upvotes: 1
Views: 315
Reputation: 1351
os.getcwd() gets the directory of where the script is executed from, and this isn't necessarily where you're script is located. Pycharm is most likely altering this path when executing the script, as it executes your script from the project path, rather than the python path.
Try os.path.abspath(os.path.dirname(os.sys.argv[0]))
instead of os.getcwd()
.
These answers have more information: os.getcwd() vs os.path.abspath(os.path.dirname(__file__))
Difference between __file__ and sys.argv[0]
Upvotes: 1