I'm creating a program to take YouTube videos and convert them into mp3's and store them in a specific folder.
Every time my program is ran, it will make sure the file directory exists as well as the folder and text file inside of it, if not, it will create these. However when running my program, it does in fact create a file in the specified directory, but it will not create the json file (which is where I will store the file path directory so the user doesn't have to input the directory every time).
The program doesn't close, it doesn't throw an error, it just simply does nothing after creating the file. It shows a blinking cursor and just idles. I'm a newbie here so I'm probably missing something very simple but. I can't figure it out, the code I'm supplying below isn't the whole program, just the function that keeps messing up:
def _check_dir_path() -> bool:
if os.path.exists(file_dir):
while True:
song_path = os.path.join(file_dir, "sp_songs")
dir_file = os.path.join(file_dir, "Song File Directory.json")
if os.path.isdir(song_path):
if os.path.isfile(dir_file):
return True
else:
sp_songs = open("sp_songs", "w")
json.dump(path_dir, sp_songs)
sp_songs.close()
continue
else:
os.mkdir(song_path)
continue
I realized I wasn't specifying a directory, I was creating a file in my python project folder but checking for that file in the specified directory which meant it'll never return true:
sp_songs = open("sp_songs", "w")
By replacing 'sp_songs' with 'dir_file' I was specifying the path:
sp_songs = open(dir_file, "w")
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)
I'm trying to create a .txt file and move it to a specified folder using the code below, but I get PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\Users\Emre\Desktop\testbot\asdf\testuser.txt'
this error which is followed by the script creating a txt file in both the directory the script is running and the directory I wanted shutil to move the txt file to. What should I do? Thanks in advance.
import shutil
file = open("{}.txt".format(source), "w")
file.write("username = {}\n".format(source))
file.write("user_points = 200\n")
file.close
shutil.move("C:\\Users\\Emre\\Desktop\\testbot\\asdf\\{}.txt".format(source), "C:\\Users\\Emre\\Desktop\\testbot\\asdf\\users")
self.bot.say(channel, "You have been successfully registered, {}!".format(source))
Your code says
file.close
when it should say
file.close()
Since you are just "mentioning" the close method rather than actually calling it, the file is not getting closed. And because it is still open, you will not be able to move it.
Note that the best practice for opening files is to use a context manager:
with open("{}.txt".format(source), "w") as file:
file.write("username = {}\n".format(source))
file.write("user_points = 200\n")
shutil.move( ...
Then the file will get automatically closed when you exit the with clause for any reason—so you don't need to worry about closing it explicitly, even if you want to return early or raise an exception.
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'm building a basic file server and my program cannot find files.
def sendfile(sock, myfile):
print 'Serving file:', myfile
print 'File exists?:', os.path.exists(myfile)
path = os.path.normpath(os.path.join(os.getcwd(), myfile))
print 'Serving file:', path
print 'File exists?:', os.path.exists(path)
These always return False even though the 'myfile' and 'path' are correct [the file is in the same directory as the server program].
IDLE works fine, but without passing to functions.
>>> print os.path.exists("/user/server/foo.txt")
True
What have I missed?
[EDIT:] Output:
Serving file: foo.txt
File exists?: False
Serving file: /user/server/foo.txt
File exists?: False
I'm almost 100% sure you're not sanitizing your input before you check if the path exists. Here's something I ran in my interpreter:
>>> from os.path import exists
>>> exists('dog.png')
True
>>> exists('dog.png\n')
False
Try stripping whitespace on path before you check if it exists.
If you read the Python documentation of os.path.exists(), it says that there are specific cases in which a file or folder exists but os.path.exists() returns false:
Return True if path refers to an existing path or an open file
descriptor. Returns False for broken symbolic links. On some
platforms, this function may return False if permission is not granted
to execute os.stat() on the requested file, even if the path
physically exists.
Not directly answering the question stated here, but I found this topic when os.path.exists() was keep giving me "False", even after using strip() or os.path.join(). In my case, I was using ~ (tylda) to point to the home directory like this:
fileName = "~/path/to/file.txt"
The best way to fix this was to use os.path.expanduser(fileName), and then check if the file exists. Alternatively restore absolute path with os.path.abspath(), followed by removig of "~" from the path (but this solution will not work in all scenarios).
os.path.exists(os.path.abspath(fileName).replace("~",""))
Maybe this will be helpful to someone.
As said in this answer
this mainly occurs do to white spaces.
I also faced this issue. It took me a lot of time to figure this out.
python has a function called strip() which removes white spaces.
if variable path_to_file consists the path to the actual file then try using
if path.exists(path_to_file.strip())
print("file exists")
else:
print("file doesn't exist")
this worked for me.
This may not answer your question directly, but you could go with the "try/except" method:
Whatever function uses the file should return an exception if the file doesn't exist (especially if it's a built-in function), and you can act accordingly. Then you have no need to check whether or not the file exists yourself. Dangerous? Perhaps, but that depends on what you are actually trying to do.
This honestly should be considered a bug if it fails due to spaces.
I have found that in some cases, the result will be spurious, depending somehow on the state of the file server. This does not happen all the time, only once in a while.
I found that with at least a 10 second delay, I could avoid a failure.
In this case, I am opening zip archives repeatedly to access specific zipped files. Prior to the attempt to open it, it checks that the path exists (and try used below this because of this strange issue). If it fails, then it waits in a loop with increasing delay. I found that it usually winds up finding the file exists again after 4 loops (10 sec delay).
Here is the output of my loop print statements:
Archive r:\ballotimagearchive\ca_san_francisco_2020_pri\d03.zip does not exist according to os.path.exists().
Waiting 1 seconds
Waiting 2 seconds
Waiting 3 seconds
Waiting 4 seconds
After wait of 10 secs, r:\ballotimagearchive\ca_san_francisco_2020_pri\d03.zip now exists according to os.path.exists().
and the code segment that produces this.
if os.path.isfile(source_path):
print(f"Verified that {source_path} exists.")
else:
print(f"Archive {source_path} does not exist according to os.path.exists().")
# this may be a spurious problem related to using a file server.
tot_time = 0
for i in range(1,20):
print(f"Waiting {i} seconds")
time.sleep(i)
tot_time += i
if os.path.isfile(source_path):
print(f"After wait of {tot_time} secs, {source_path} now exists according to os.path.exists().")
break
else:
print(f"After wait of {tot_time} secs, {source_path} still not found according to os.path.exists().")
sys.exit(1)
os.path.exists returns false also if the given path is longer than 256 characters.
I was getting this problem fairly often until I tried adding getcwd(), now it never fails
os.path.join(os.getcwd(), source_file)
I had this same issue and found the following solution:
Using the OS's native directory separator '\' or '/' even on Windows, using the forward slash in all occasions works just fine for me. os.sep can help.
In addition to this, sanitizing the path string a bit similar to this:
import re
from os import path
strPath = "c:/dir1/dir2/dir3/dir4/important-file.ext"
strPath = re.escape(strPath)
bTest = os.access(strPath, os.F_OK)
# or the classic
bTest = path.exists(strPath)
print(bTest)
I want to use the file in the Downloads folder on ubuntu, but os.path.exists can't find using the absolute path ~/Downloads/filename.txt.
Then I use os.path.abspath('') to get the root path /home/yourPCname/ and replace ~, it works!