Python Forum
delete file with handling - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: delete file with handling (/thread-21739.html)



delete file with handling - 3Pinter - Oct-12-2019

Hi,

So I want to delete some files and if a file is in use, the script should print an error.
However I don't care for the error report if the file doesn't exists.
So only "in use " should e raised.

(Python 2.7)

At first I thought:
try:
    os.remove(data_file)
except OSError as e:
	print("Error: file {}, {}".format(data_file, e.strerror))
But that obviously returns all errors, including 'file doesn't exist'.

my remaining option is to include a os.filepath.exists.
if os.filepath.exists(data_file):
   try:
        os.remove(data_file)
   except OSError as e:
	    print("Error: file {}, {}".format(data_file, e.strerror))
OR knowing the error of file in use (32 if I'm correct)
try:
    os.remove(data_file)
except OSError as e:
	if e.strerror.startswith("[Errno 32]"):
		print("Error: file {}, {}".format(data_file, e.strerror))
Am I right?


RE: delete file with handling - 3Pinter - Oct-17-2019

Anybody a thought?

(sorry small bump :) )