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.
Related
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 am writing my script's output to an Excel file using openpyxl, which is working fine. However, if the Excel file is accidently open while Python is trying to write to it, it shows a PermissionError- which is expected. On this case, what I would have preferred is to write somehow rather than showing the error. Is there a way to do this?
You can't really solve this because the problem is not with openpyxl per-se, rather with the file you manually opened. If you would have opened it as a Read-Only file, you will not get that error. Of course, you can't (easily) solve that programmatically as openpyxl is not aware of the open instances of Excel you have running in the background.
Note that when opening the file as read-only, you will not see the saved changes from openpyxl.
One possible workaround, to avoid losing your changes you were about to save, is to allow the user to close that instance of Excel and try to save again. Something like:
while True:
try:
wb.save(path)
except PermissionError:
input(f"Please close the excel {path} and press Enter")
else:
print(f"Excel file saved successfully at - {path}")
break
Alternatively save to a temporary file and let the user merge later:
from pathlib import Path
try:
wb.save(path)
except PermissionError:
path = Path(path)
temp_path = path.with_name(f"{path.stem}_temp{path.suffix}")
wb.save(temp_path)
print(f"Excel file saved temporarily at - {temp_path}")
else:
print(f"Excel file saved successfully at - {path}")
Warning: these might cover-up other possible PermissionErrors, so use with care.
I've had a script for a while that has been running without issues however recently had a "hitch" with a temporary file that was within a directory.
The file in question started with '~$' on a windows PC so the script was erroring out on this file as it is not a proper DOCX file. The file in question was not open and occurred after being transferred of a network drive onto an external hard drive. Checking the destination drive (with hidden files on etc) did not show this file either.
I have attempted a quick fix off:
for (dirpath,dirnames,filenames) in os.walk('.'):
for filename in filenames:
if filename.endswith('.docx'):
filesList.append(os.path.join(dirpath,filename))
for file in filesList:
if file.startswith('~$'):
pass
else:
<rest of script>
However the script appears to be ignoring this to proceed then error out again, as the file is not "valid".
Does anyone know either why this isn't working or a quick solution to get it to ignore any files that are like this? I would attempt a if exists, however the file technically does exist so this wouldn't work either.
Sorry if its a bit stupid, but I am a bit stumped as to A. why its there and B. how to code around it.
In the second code block, your variable file contains the whole file path, not just the file name.
Instead skip the "bad" files in your first block instead of appending to the list:
for (dirpath,dirnames,filenames) in os.walk('.'):
for filename in filenames:
if filename.endswith('.docx'):
if not filename.startswith('~$'):
filesList.append(os.path.join(dirpath,filename))
The other option would be to check os.path.basename(file) in your second code block.
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 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.