Got some weird behavior here. Basically I am using import os to find the path of the exe file and then I use that path in a batch file to move the exe file. I've also used pyinstaller to make the program an exe.
Now here is where the issue occurs. The os commands works well, but it thinks the file is still a .py
This is really odd because I made this variable:
dirName = os.path.abspath(__file__)
Now, this finds the correct directory and the correct file name(but not file type)
Then I use that variable to write down which directory the file is currently in like this:
move.write('move /Y "' + str(dirName) + '" (code continues here, but not important)
This works when the file is a .py but not when it is a .exe
I hope this makes sense, feel free to ask and/or edit if anything is unclear.
Current output: The system cannot find the file specified.
Wanted output: 1 file(s) moved.
You can specify the extension you want by this way:
files = os.listdir('/your/directory')
for filename in files:
if filename.endswith(".exe"):#or extension you want
#copy file you want
Related
I am trying to simply build a program, which reads another file. When I try to run the code I get the error mentioned in the topic. I've already tried to take the full path, but it wasn't working.
Do you have any ideas to solve the problem?
file = open("Text.txt")
vari = file.read()
print(vari)
When you're launching from a command line, the current working directory may not be the same as the home directory of your top-level file (i.e., the directory where your program file resides).
If you run it in cmd.exe (Command Prompt), then path to file "Text.txt" will be searched for in the directory currently opened in the Command line. Usually, C:\Users\[user]\ is the default working directory on Windows.
You need to run your program using Python interpreter/Py Laucher, that is usually opened on double click on *.py top-level program file or simply change the current directory in Command prompt with cd <TOP_LEVEL_FILE_DIR>.
You have to add the full path above file = open("Text.txt") line to indicate where this file is located. Adding the full path to the open(/path/to/where/this/text.txt) like an example is required in this case (so even if your main program is not in the same directory as the file you're trying to open, it will still work). There are many examples on SO, that show how this can be achieved.
Try the following code,
To open the file, use the built-in open() function.
fileLocation = open("C:/Users/Desktop/Text.txt", "r")
vari = fileLocation.read()
print(vari)
"r": read file "w": write file
It will read the file and will display the contents of the file.
Make sure you use the forward slash in the path.
I am working through Learn Python the Hard Way but am having a problem with an exercise that reads a file: https://learnpythonthehardway.org/python3/ex15.html
I have followed this and made sure my file is in the same folder as my python file. I keep getting the error:
Traceback (most recent call last):
File "ex15.py", line 5, in <module>
txt = open(filename)
FileNotFoundError: [Errno 2] No such file or directory: 'ex15_sample.txt'
I am entering: python ex15.py ex15_sample.txt into the powershell. I tried looking up the problem I'm having but could not find anything that helped in my case. Let me know if I am doing something wrong or if I'm missing something. Thanks
You can check your current path and whether your file exists by
import os
#get the current working directory
os.getcwd()
#check whether your file exists in the current working directory
os.path.exists("./ex15.py")
try 2 things below
Check both files .py and .txt are at same location. and then execute program.
this is how i ran the code.
C:\Users\db\Desktop\Python>python ex15.py
enter File Name: ex15_sample.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
If your file is at other location you need to provide absolute path for your file. as
C:\Users\db\Desktop\Python>python C:\Users\deepakb\Desktop\ex15_sample.txt
i had my txt file at desktop this time.
A brief demonstration on working directory and relative file locations..
Say we have a text file named hello.txt with the contents:
Hello World!
that is located at "C:\Users\username\Documents\python\hello.txt"
And we have a python script named script.py with the contents:
with open('hello.txt', 'r') as f:
print(f.read())
Which is located at "C:\Users\username\Documents\python\script.py"
If I just hit the windows key and type power shell and hit enter to open it, I'll see it by default gives me a prompt at my home directory: "C:\Users\username>". From here I can execute my python script by calling C:\Users\username> python C:\Users\username\Documents\python\script.py. If I do this, however, they python interpreter would have started in my home folder, and when it tries to find "hello.txt" it will only search through the folder "C:\Users\username". That's not where the file is, so we get a file not found error.
To resolve this we have a few options. Number one is to re-write our script file to include the full path of our text file: ... open("C:/Users/username/Documents/python/hello.txt", ... This way there is no searching necessary, and the script can be run from anywhere. Another option is to change the working directory of the interpreter from within the script. You can set the working directory with the os library by calling os.chdir('C:/Users/username/Documents/python'). Finally you can set the working directory with PowerShell before calling the python interpreter using the cd command:
C:\Users\username> cd .\Documents\python\
I had the same error.
It was a mistake from me naming the file as ex15_sample.txt.
When you are creating a file in notepad, the file name would be automatically .txt
so if you have created a file just rename it as ex15_sample.
or
You can also run the same program by giving python ex15.py ex15_sample.txt.txt
As you can see the file name might be ex15_sample.txt with a .txt extension.
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.
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...
Anyone reading this in 2021... I've just run into similar issue with Pyinstaller. Needed to add a text file to my python code:
pyinstaller --add-data "/my/path/to/mytextfile.txt:/path/mytextfile.txt" mypython.py --onedir or --onefile
No matter if onedir or onefile, my code just never found the text file. Infact it threw the error:
IsADirectoryError: [Errno 21] Is a directory: /path/mytextfile.txt
Which didn't make sense to me because that's a file not a folder. Only when I checked this with the --onedir flag and I followed the path, I realized that pyinstaller would not only create a folder path, but also folder mytextfile.txt and put mytextfile.txt in there... so really the --add-data flag only wants a destination folder not the path to the file.
pyinstaller --add-data "/my/path/to/mytextfile.txt:path" mypython.py
or in the spec file i.e mypython.spec
datas=[('/my/path/to/mytextfile.txt', 'path')]
Should fix this. Note also the "DATA" configuration in the spec file is gone.
I am using Vizard to create an .exe file off a python script. I need this script to create a folder which resides next to the .exe file
if getattr(sys, 'frozen', False):
logging.warning('Application is exe')
loggingPath = os.path.dirname(sys.executable)
logging.warning(os.getcwd())
elif __file__:
loggingPath = os.path.dirname(__file__)
logging.warning('Application is script')
logging.warning(os.getcwd())
if not os.path.exists(loggingFolder):
logging.warning('Directory not existing... creating..')
os.makedirs(loggingFolder)
works fine when I execute from the IDE, but in an exe file it throws data in the Appdata Folder in Windows/Users/Temp/randomfoldername.
Also, I always Application is script, even when its packed into exe.
Can someone point me in the right direction here?
Thanks in advance
The sys module does not have any attribute frozen, which results in the first if statement always returning False.
sys.executable will give the path to the python interpreter binary, ie. for Windows the path of your python.exe file, which I cannot see why you would need for this.
If what you want is to ensure that the file running is a .exe file, then make a folder next to it, it may be simpler to just check if the filename ends with .exe?
if __file__.endswith('.exe'):
loggingFolder = os.path.join(os.path.dirname(__file__), 'foldername')
if not os.path.exists(loggingFolder):
os.makedirs(loggingFolder)
if you just want to create a folder at runtime, then another (possibly easier) method is to run your vizard program from within a batch file and create the folder first in the batch file
e.g. create run_viz_prog.bat with content like this :-
mkdir new_folder
my_viz_prog.exe
Both files, the .py file and a .txt file it calls with
champions_list = open('champions.txt','rU').read().split('\n')
are in the file folder C:\Users\[My Name]\Programming\[file name].
I'm calling the .py file through Command prompt and it returns the error
IOError: [Errno 2] No such file or directory: champions.txt
Has this happened to anyone else before?
When you open a file with open('champions.txt'), then the OS expects to find the champions.txt file in the current directory. The current directory is the directory of the command prompt window where you started the program. This is not (necessarily) the same as the directory where the Python script is stored.
You may be able to fix this by doing:
import os
import sys
open(os.path.join(os.path.dirname(sys.argv[0]), 'champions.txt')
This takes the full name of the script in sys.argv[0], takes the directory part, and then joins that to the file name you want. This will open the file in the script directory, not the current directory.
(Note that using sys.argv[0] in this way is OS-dependent, and works on Windows but may not work the same way on other systems.)
Just because the file is in the same folder as the script does not mean the python interpreter knows that the file is there. It is looking for a file in the cwd. You can:
Try using the full absolute path of the file; or
Add the directory containing the file using os.path.append