0

I'm trying to remove a file that physically exists on my system. I wrote the following function using Python 3 that does not work:

def remove_file(output_file):
    print("Removing the output file: ", output_file)
    try:
        os.remove(output_file)
    except RemoveFileError as e:
        remove_stat = e.returncode
    else:
        remove_stat = 1
    if remove_stat == 0:
        print("File removed!")
    else:
        print("File not removed.")

When I try to remove the file using the above code this is the result I get:

Removing the output file:  ../../../output_files/aws_instance_list/aws-master-list-03-21-2019.csv
File not removed.

What am I doing wrong?

5
  • 2
    Change remove_stat = 1 to remove_stat = 0. Commented Mar 21, 2019 at 15:59
  • 1
    remove try and except block to show the real error. only write os.remove(output_file) to see what is the real error Commented Mar 21, 2019 at 15:59
  • 4
    You're setting remove_stat to 1 in the else, which is executed when no exception is raised. Commented Mar 21, 2019 at 16:00
  • So you set remove_state to 1 upon success, but then you check that it's equal to 0 to see if it was successful? When would that condition ever happen? Commented Mar 21, 2019 at 16:00
  • You need to add a statement before removing the file. Probably a checking to see whether the file exists or not. Or maybe you are passing the wrong file location. Commented Mar 21, 2019 at 16:02

1 Answer 1

2

The else clause of your try statement is being executed when no error occurred. See Handling Exceptions

Try this updated version of your code:

def remove_file(output_file):
    print("Removing the output file: ", output_file)
    try:
        os.remove(output_file)
    except RemoveFileError as e:
        remove_stat = e.returncode
    else:
        remove_stat = 0
    if remove_stat == 0:
        print("File removed!")
    else:
        print("File not removed.")
    print("File exists:", os.path.exists(output_file))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.