Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
delete file with handling
#1
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?
Reply
#2
Anybody a thought?

(sorry small bump :) )
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  File Handling not working properly TheLummen 8 561 Feb-17-2024, 07:47 PM
Last Post: TheLummen
  file handling Newbee question middlecope 2 744 Jan-18-2023, 03:09 PM
Last Post: middlecope
Star python exception handling handling .... with traceback mg24 3 1,215 Nov-09-2022, 07:29 PM
Last Post: Gribouillis
  Delete multiple lines from txt file Lky 6 2,201 Jul-10-2022, 12:09 PM
Last Post: jefsummers
  File handling issue GiggsB 4 1,392 Mar-31-2022, 09:35 PM
Last Post: GiggsB
  Find and delete above a certain line in text file cubangt 12 3,353 Mar-18-2022, 07:49 PM
Last Post: snippsat
  How can I solve this file handling issue? GiggsB 17 3,417 Feb-14-2022, 04:37 AM
Last Post: GiggsB
  How to delete portion of file already processed? Mark17 13 2,635 Jan-22-2022, 09:24 AM
Last Post: Pedroski55
  How to solve this file handling issue? GiggsB 3 1,631 Jan-10-2022, 09:36 AM
Last Post: Gribouillis
  delete a file works but with error Leon79 4 2,873 Jul-14-2020, 06:51 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020