I have created an exe file using autopy to exe.
At the beginning, I ask the user to enter the file to use using the following code:
filename = filedialog.askopenfilename(initialdir="/", title="Select file to convert")
But when the user click on "Cancel" or hit the "X" in the upper right side, an error code appear as you can see on the image
how to stop the code from continue running if the user click one of the two option mentioned above so that the error code will not appear?
I know some questions have already been asked about similar subject but I couldn't adapt them to my case. I hope I have been clear enough
The root cause of the FileNotFoundError is that it cannot find the file with an empty string path, which it will never find that one.
I will elaborate on what #Sagitario has explained. The os.path.exists(filename) used to check if the filename is valid and exists or not:
import os
if os.path.exists(filename):
do_something() # like trying to open a file in this condition.
else:
print(f"{filename} not found, please select other path")
Nevertheless, if your path is empty, it will surely go in an else condition. Instead, you can check the path input that it's not empty and exists.
In addition, the try-except block can help handle the error here. But you also need to solve the main problem of an empty file path somewhere in your code, by using the above if condition to verify the file path.
try:
filename = filedialog.askopenfilename(initialdir="/", title="Select file to convert")
# ... the rest of your code relating the file opening ...
except FileNotFoundError:
print(f"{filename} not found, please select other path")
Just check if the provided path exists with os.path.exists(filename)
Related
I'm really new to coding sorry if my questions sound stupid. I've created a program and I need it to delete any temporary files created during runtime.
So far the first error I've stumbled upon is insufficient permissions to delete a folder, hence the try-except for PermissionError.Secondly I need to upload this to a trinket.io link to test it and send it to be graded but nothing seems to be deleted there and no permission errors either? Seems like the whole function is getting skipped. Here is what i have so far on the file-deleting function. It keeps only the 4 necessary files...
def clear_temps():
c=os.getcwd()
d=os.listdir(c)
for file in d:
if '.py' in file or '.csv' in file and not file=='mytemp.csv':
pass
else:
if os.path.isdir(file):
os.path.split(file)
try:
os.remove(file)
except PermissionError:
pass
The code you wrote should work fine. Try it in a local Python editor to check it for sure.
I have noticed that in trinket when you delete a file the tab is not removed, but if you check in the folder the file is not there.
You can use this code to check out if the file is still there:
def clear_temps():
c=os.getcwd()
d=os.listdir(c)
for file in d:
if '.py' in file or '.csv' in file and not file=='mytemp.csv':
pass
else:
if os.path.isdir(file):
os.path.split(file)
try:
print(os.path.isfile(file))
os.remove(file)
print(os.path.isfile(file))
except PermissionError:
pass
I added an check if the file exists before and after the remove.
So in case of an output : True False the file in trinket has been really deleted and in case of an True True the file is still there.
I've got a problem that has been troubling me for nearly a week. It was an exercise given out in class (not as homework) for us to try and find the answer to. The question is:
"Write a program that prompts the user to enter the name of a file, and then determines whether or not that file exists. The program should not alter the contents of the file (if it does exist) in any way.
For simplicity, check only the directory/folder in which your program exists (so do not worry about drives, directory path names and so on).
Hint: A promising way to do this would be to attempt to open the file and observe results."
I've created a file called 'hello.txt' and put it in a seperate folder called 'Test Folder' and tried to get it to work so many times but I'm getting no where. Any ideas?
#!/usr/bin/python
import sys
import os.path
fileName = sys.argv[1]
print(os.path.isfile(fileName))
From this question: How do I check whether a file exists using Python?
The first thing to do here is decompose the requirements and deal with each separately.
Prompt the user for a filename
Determine whether "that file" exists.
Implicitly - report the answer to 2.
You need to be able to do both (3 should be obvious), and realize that by "that file exists", what is really meant is whether a file with that name exists.
Try either of the two, or both by running the python interpreter. If you still need help, show what you have done.
I'm writing a script to save a file and giving the option of where to save this file. Now if the directory entered does NOT exist, it breaks the code and prints the Traceback that the directory does not exist. Instead of breaking the code I'd love to have have a solution to tell the user the directory they chose does not exist and ask again where to save the file. I do not want to have this script make a new directory. Here is my code:
myDir = input('Where do you want to write the file?')
myPath = os.path.join(myDir, 'foobar.txt')
try:
f = open(myPath, 'w')
except not os.path.exists(myDir):
print ('That directory or file does not exist, please try again.')
myPath = os.path.join(myDir, 'foobar.txt')
f.seek(0)
f.write(data)
f.close()
This will get you started however I will note that I think you need to tweak the input statement so the user does not have to put quotes in to not get an invalid syntax error
import os
myDir = input("Where do you want to write the file ")
while not os.path.exists(myDir):
print 'invalid path'
myDir = input("Where do you want to write the file ")
else:
print 'hello'
I do not know what your programming background is - mine was SAS before I found Python and some of the constructions are just hard to think through because the approach in Python is so much simpler without having a goto or similar statement but I am still trying to add a goto approach and then someone reminds me about how the while and while not are simpler, easier to read etc.
Good luck
I should add that you really don't need the else statement I put it there to test/verify that my code would work. If you expect to do something like this often then you should put it in a function
def verify_path(some_path_string):
while not os.path.exists(some_path_string):
print 'some warning message'
some_path_string = input('Prompt to get path')
return some_path_string
if _name_ == main:
some_path_string = input("Prompt to get path")
some_path_string = verify_path(some_path_string)
import os
path=r'C:\Users\User\Documents\prog'
folderlist=os.listdir(path)
def is_file_contain_word(folderlist,query_word):
for file in folderlist:
if query_word in open(folderlist).read():
print (file)
print("finishing searching.")
query_word=input("please enter the keyword:")
is_file_contain_word(folderlist,query_word)
This is what I have so far. It has returned that I have type error:
invalid file: ['1.doc', '1.odt', 'new.txt']
I got this error when I swapped path with folderlist in the open
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\God\\Documents\\prog'
import os
This is my new code:
import os
path=r'C:\Users\God\Documents\prog'
folderlist=os.listdir(path)
print(folderlist)
def is_file_contain_word(folderlist,query_word):
for i in os.listdir(path):
if query_word in i:
print("Found %s" %query_word)
else:
print("not found")
query_word=input("please enter the keyword:")
is_file_contain_word(path,query_word)
This goes through each of the 3 files to search for the filename. It only stops when it finds it or it goes through it.
You are making multiple mistakes here:
First, try to indent your code correctly:
def is_file_contain_word(folderlist,query_word):
for file in folderlist:
if query_word in open(folderlist).read():
print (file)
print("finishing searching.")
Then the real problem.
open(folderlist) should be open(file), as I believe that's your intention.
And that's one reason why the program won't run: open(folderlist) opens C:\Users\User\Documents\prog, which is a directory and will cause problem.(You probably thought this line opens all files contained in that folder)
BTW, don't use "file" as a var, it's a reserved word in python.
However, even though you fix this part, the original function still won't work.
def is_file_contain_word(folderlist,query_word):
for f in folderlist:
if query_word in open(f).read():
print (f)
print("finishing searching.")
Why? If you check this folderlist(folderlist=os.listdir(path)), it would be something like:
["Prog's Movies", "Homework3.pdf", "blahblah.txt"]
Which is problematic because first, you can't open them because they aren't absolute path(Like C:\Users\God\Documents\prog\blahblah.txt), second, listdir would also list all directories(In this case "Prog's Movies" directory), which you can't use open to open them.
At last, if you are running this on command line, don't make two folderlist vars. I know in this case it won't cause problem, but it dose reduce your code's readibility and seem to confuse you a little bit.
How to fix it?
How to list all files of a directory?
Here is a nice answer to how to open all files in a directory correctly.
I am trying to write a detector that checks if a certain directory can be deleted using shutil.rmtree. I have a partial code finished as below that now works partial.
This code is now able to gives warning when any .exe files under the target folder is still running. But, this code is not yet able to flag warnings if any particular file under a folder is opened by an editor (which is another cause that makes a directory not deletable). Any guidance will be appreciated. Thanks in advance
Note: I've used open method to check for any locked file.
def list_locked_files(dir):
isLocked = False
for name in os.listdir(dir):
uni_name = unicode(name)
fullname = dir + u'/' + uni_name
if os.path.isdir(fullname):
list_locked_files(fullname)
else:
try:
f = open(fullname, 'r+')
f.close()
except IOError:
print fullname + u' is locked!'
isLocked = True
if isLocked is True:
print u'Please close the files/dir above !'
sys.exit(0)
It is not necessarily possible to determine whether a file deletion will succeed or fail on Windows. The file could be opened in a fully permissive share mode which means another attempt to open the file will succeed (no matter what kind of access you request).
The only way to tell whether a file can be deleted is to actually try it.
Even if there were an accurate way to tell beforehand, once you get the information it is instantly out of date. For example, after you call list_locked_files, a program could open another file in that directory which would cause rmtree() to fail.