What code should I use to prevent removing missing files?

Asked 2 years ago, Updated 2 years ago, 14 views

What code should I use to prevent removing missing files? I'd like to know it in a Python way, so please check if it's right for me to use

if os.path.exists(filename):
    os.remove(filename)

python

2022-09-21 15:51

1 Answers

If it's a more Python way

try:
    os.remove(filename)
except OSError:
    pass

There is. Of course, it's longer than the code you posted, but it's more efficient because you don't have to call os.path.exists(filename).

If you squeeze the code more accurately in the exception part, you need to pass only "if there are no files to remove."

import os, errno

def silentremove(filename):
    try:
        os.remove(filename)
    exceptionOSError as e: # 2.6 and below "exceptionOSError, e:"
        if e.errno != errno.ENOENT: 
            Rise #errno.ENOENT = no so much file or directory, raise again


2022-09-21 15:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.