GUI App shows File not found in directory Error - python

I made a GUI for a python program that allows me to read a csv file and display the data on the GUI. The GUI works perfectly fine when I run the program through IDLE. However when I try to run the program file as it is from Windows Explorer it shows the following error.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Python\gui1.py", line 43, in find_result
with open("RESULTS.csv") as a:
FileNotFoundError: [Errno 2] No such file or directory: 'RESULTS.csv'
This is the program code:
import tkinter as tk
import csv
root=tk.Tk()
root.title('Results')
tk.Label(root,text="Enter your Roll Number:").grid(row=1,column=1,sticky=tk.W)
tk.Label(root,text="Name:").grid(row=4,column=1,sticky=tk.W)
tk.Label(root,text="Total (Core 5 Subjects):").grid(row=5,column=1,sticky=tk.W)
tk.Label(root,text="Total (Best 5 Subjects):").grid(row=6,column=1,sticky=tk.W)
tk.Label(root,text="Percentage:").grid(row=7,column=1,sticky=tk.W)
tk.Label(root,text="Rank:").grid(row=8
,column=1,sticky=tk.W)
rno=tk.StringVar()
name_=tk.StringVar()
t1_=tk.StringVar()
t2_=tk.StringVar()
perc_=tk.StringVar()
rank_=tk.StringVar()
tk.Entry(root, textvariable=rno,justify=tk.RIGHT).grid(row=1,column=2,padx=3,pady=3)
def find_result():
tk.Label(root,textvariable=name_,justify=tk.RIGHT).grid(row=4,column=2,sticky=tk.E)
tk.Label(root,textvariable=t1_,justify=tk.RIGHT).grid(row=5,column=2,sticky=tk.E)
tk.Label(root,textvariable=t2_,justify=tk.RIGHT).grid(row=6,column=2,sticky=tk.E)
tk.Label(root,textvariable=perc_,justify=tk.RIGHT).grid(row=7,column=2,sticky=tk.E)
tk.Label(root,textvariable=rank_,justify=tk.RIGHT).grid(row=8,column=2,sticky=tk.E)
with open("RESULTS.csv") as a:
reader=csv.reader(a)
for i in reader:
if i!=[]:
if i[0]==rno.get():
name=i[1][2:]
t1=i[19]
t2=i[20]
perc=i[21]
rank=i[22]
name_.set(name)
t1_.set(t1)
t2_.set(t2)
perc_.set(perc)
rank_.set(rank)
tk.Button(root, text="Check your Result",command=find_result).grid(row=2,column=2)
root.mainloop()
Opening program with IDLE:
Opening program through Explorer:

open("RESULTS.csv") looks for that file in the current working directory, whatever that happens to be. This must be different for the two different ways you run the code. Do one of the following.
Give open an absolute path to the file instead of a relative one. If you know the location of the data file relative to the location of the program file, use __file__, which has the location of the program file, as the starting point. Note 1: that when working interactively, without running a file, __file__ does not exist. Note 2: If you do not understand 'absolute path', do a web search.
Explicitly set the current directory to the one containing the file with os.chdir(path). where path is absolute, not relative. This is more useful if opening several files in that directory.

Related

Text file within the same directory as main Python file not found

I have the next files inside a folder:
When I execute idsave.py from within PyCharm or from the file location inside the command line it opens this file selection window when it's supposed to do it:
But if I run the desktop shortcut I made, it does not ask me to choose a file, when running gtk-launch idsave.desktop and click the button that triggers said window I get the next error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib64/python3.9/tkinter/__init__.py", line 1892, in __call__
return self.func(*args)
File "/home/username/Programacion/Python/idsave/idsave.py", line 39, in open_file
dir_path = open('dir.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'dir.txt'
Even though when checking if the file exists with os.listdir() it shows that the file in fact exists:
print(os.listdir(dir))
[file, file, file, 'dir.txt', 'idsave.py', file, file]
My .desktop shortcut looks like this:
[Desktop Entry]
Name=IdSave
GenericName=Idea Saver
Comment=Save Your Ideas
Exec=/home/username/Programacion/Python/idsave/idsave.py
Icon=/home/username/Programacion/Python/idsave/icon.jpg
Type=Application
Categories=Development;
The function that triggers that window is this:
def open_file():
dir_path = open('dir.txt', 'r')
root.filename = filedialog.askopenfilename(
initialdir=dir_path.readline(),
filetypes=(("All Files", "*.*"))
)
dir_path.close()
I already tried with './dir.txt' '../dir.txt' and the absolute path of the file, but the desktop entry still gives me the same error.
What am I doing wrong?
Instead of creating a desktop shortcut, you can create a bash script (.sh file) with the following code in a text editor and place it on your desktop. Name it idsave.sh.
cd "/home/username/Programacion/Python/idsave/"
python3 idsave.py
If on double-clicking the script doesn't run and opens your text editor instead, you can right click on idsave.sh and click on Properties. Then click on the Permissions tab and check Allow executing file as program (or something similar). Then click on OK.
Now you will be able to double click on idsave.sh and your Python program will launch as expected.
This will probably solve your problem.

Move file in Python with shutil that has just been changed

I wrote a Python script which calls subprocess which will create a file:
subprocess.run(["youtube-dl.exe", "-o " + fileName, link])
After that I'd like to move my file to a different directory:
shutil.copy("C:\\Users\\***\\Desktop\\m2.m4a", "C:\\Users\\***\\Desktop\\Songs\\m2.m4a")
But that gives me the following error:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\***\Desktop\m2.m4a'
But the file definitely exists. I tried to move a file which has not just been altered, and it works.
In case Windows needs time to create the file properly, I paused the code after the file creation and before the shutil.move-command:
time.sleep(4)
But it still doesn't work. Is it maybe because subprocess is still running and shutil can't access the file at the same time? Or because Python doesn't know that a new file has just been created? Thanks for your help!

Python script won't execute batch file in IIS 7.5

I have a python script that automates Erdas image processing software based on parameters gathered by the script from the image metadata. The python script gathers these parameters into list which gets written to a batch file, and then runs the batch file, which tells the Erdas software to process the images. When I run this outside of the IIS directory, the script works perfectly. However, when I run the script within the IIS directory, the script partially runs, but gives me an error message when it tries to run the batch file. Just an FYI, I've searched everywhere for a solution to this problem. I've tried changing folder and file permissions and IIS manager settings with no luck. Here is the error message:
Traceback (most recent call last):
File "python_page.py", line 1018, in <module>
main()
File "python_page.py", line 1002, in main
getAtmCorrectBatchFile(AtmCorrectBatchlist)
File "python_page.py", line 912, in getAtmCorrectBatchFile
f = open(basePath + '/atm_batch_process.bat', 'w')
IOError: [Errno 13] Permission denied: 'C:/inetpub/wwwroot/cgi-bin/atm_batch_process.bat'
Below is the code where the error is occurring. What I'm most confused about is that the error is located within the getAtmCorrectBatchFile() function that creates the batchfile, but the error arises when the script tries to call the RunAtmCorrectBatch() function listed directly below it. The script has successfully created the batch file and saved it in the cgi-bin directory at this point, so why would the error be within the function that creates the batch file instead of the one that tries to run the batch file?
Edit: I can right click the batch file within the cgi-bin directory and select run, which successfully outputs the processed images, just for some reason this doesn't work when the python script tries to run the batch file.
def getAtmCorrectBatchFile(batchlist):
f = open(basePath + '/atm_batch_process.bat', 'w') #line 912
for i in range (0, len(batchlist)):
f.write(str(batchlist[i]).replace('\\', '/') +'\n')
f.close()
def RunAtmCorrectBatch():
try:
from subprocess import Popen
p = Popen("/atm_batch_process.bat", cwd=basePath)
stdout, stderr = p.communicate()
except WindowsError:
pass

(Error 2) No such file or directory in Python 3

I'm trying to display text from a file but am getting the mentioned error. I've tried changing the default directory using os.chdir(). I'm also getting the error even if I save the text file in the default directory. I'm using version 3.2.
Code:
from sys import argv
import os
script, filename = argv
txt = open(filename)
print(filename, "is the filename.")
print("Here is the text.", txt.read())
filename_again = input("Filename again pls.")
txt_again = open(filename_again)
print("Test again.", txt_again.read())
Error Report:
PS C:\Python32\Stuff\Programs> python Sample1.py fubar1.txt
Traceback (most recent call last):
File "Sample1.py", line 6, in <module>
txt = open(filename)
IOError: [Errno 2] No such file or directory: 'fubar1.txt'
PS C:\Python32\Stuff\Programs>
Tested the code and it worked for me. Tried to enter this as a comment, but don't have the points.
Tested on a Mac OS X Yosemite 10.10.2 using python 3.4.2
May I suggest it may have been a typo when entering the original filename? I tried different file names and it worked successfully. If this is not the case then debugging time.
Note Error Line
The error is encountered in the first open statement so it is possible that the arguments text needs to be trimmed.
Debugging Idea
Noticed you are in windows. Try using a print() command on line 5 to examine the contents of the filename variable. You may have spaces before or after the filename which are then causing the open statement to fail.

Opening a file in pwdir's folder in Python through Applescript

Opening a file available in present working directory's temp folder in python
I tried
pwdir=os.getcwd()
tempdir=pwdir+"/temp/test.txt"
f=open(tempdir,'r+')
When I print the path of tempdir, it is showing up correctly and also the contents of file are also read.
When I try to combine this operation from an Applescript, which calls this python script. I get an error like this
f=open(pwdir1,'r+')
IOError: [Errno 2] No such file or directory: '//temp/test.txt'" number 1
EDIT:
I am using Shell script from Applescript to call this pythonscript
do shell script "/Users/mymac/Documents/'Microsoft User Data'/test.py"
EDIT:
Python Code:
tempdir = os.path.join(os.getcwd(),'temp','htmlinput.html')
print tempdir
with open(tempdir) as f:
html=f.read()
Python output from terminal:(works perfectly fine)
/Users/mymac/Documents/Microsoft User Data/Outlook Script Menu Items/temp/htmlinput.html
I am also able to see the file contents.
Applescript Code:
do shell script "/Users/mymac/Documents/'Microsoft User Data'/'Outlook Script Menu Items'/new.py"
Applescript Error:
error "Microsoft Outlook got an error: Traceback (most recent call last):
File \"/Users/mymac/Documents/Microsoft User Data/Outlook Script Menu Items/new.py\", line 12, in <module>
with open(tempdir) as f:
IOError: [Errno 2] No such file or directory: '/temp/htmlinput.html'" number 1
I don't know Applescript -- or OS X in general. It looks like the script is being run from the root folder, and os.getcwd() returns '/'. The directory of the script itself is sys.path[0] or the dirname of the current module -- dirname(__file__) -- if it's a single script instead of a package. Try one of the following
import os, sys
tempdir = os.path.join(sys.path[0], 'temp', 'temp.txt')
or
import os
tempdir = os.path.join(os.path.dirname(__file__), 'temp', 'temp.txt')
The double slash is your problem. The right way to join file and path names in Python is with os.path.join. Try:
tempdir = os.path.join(os.getcwd(), 'temp', 'test.txt')
Also, you should probably be doing:
with open(tempdir) as f:
which will make sure tempdir gets closed even if you have an error.
Edit:
We need to see what tempdir is when the script is invoked by the AppleScript, not when it is invoked from the terminal. If you do
tempdir = os.path.join(os.getcwd(),'temp','htmlinput.html')
with open('/Users/mymac/Documents/temp.txt', 'w') as fwrite:
fwrite.write(tempdir)
What exactly ends up in the file /Users/mymac/Documents/temp.txt?

Categories

Resources