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.
-
"when I convert it to an executable it does not work" - you have to elaborate a bit more about this step.yedpodtrzitko– yedpodtrzitko2017年02月05日 23:07:22 +00:00Commented Feb 5, 2017 at 23:07
-
@yedpodtrzitko When I use pyinstaller to convert the .py to a .execWild Mike– Wild Mike2017年02月05日 23:10:35 +00:00Commented Feb 5, 2017 at 23:10
-
run .exe it in console/terminal to see errors.furas– furas2017年02月05日 23:17:14 +00:00Commented Feb 5, 2017 at 23:17
-
it doesn't need terminal to copy it.furas– furas2017年02月05日 23:19:06 +00:00Commented Feb 5, 2017 at 23:19
-
@furas When I run the executable the terminal opens up. If I manually go to where the exec is located in terminal and do ./name it works. But I want the terminal to open up to where the executable is located automatically and run the rest of the code when I click it.Wild Mike– Wild Mike2017年02月05日 23:22:43 +00:00Commented Feb 5, 2017 at 23:22
1 Answer 1
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__))
3 Comments
os.path.abspath(os.path.dirname(os.sys.argv[0])) I tested this one and it worked for me.