Python Forum

Full Version: delete file with handling
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
Anybody a thought?

(sorry small bump :) )