cc6g11
cc6g11

Reputation: 487

Delete a file if it exists. If it doesn't, create it

Title says all.

My code:

 try:
        os.remove("NumPyResults.txt")

 except IOError:

        with open("NumPyResults.txt", 'a') as results_file:
            outfile = csv.writer(results_file)
            outfile.writerow(.......)

The reason it is in append is because it is in a function and called numerous times. So I want a new file every time I run the program, by deleting the old one and writing the new one.

However this does not create a new file. I also created the file in the directory I am running from and it doesn't delete it either.

I get

WindowsError: [Error 2] The system cannot find the file specified: 'NumPyResults.txt'

Upvotes: 4

Views: 11268

Answers (1)

Robert E
Robert E

Reputation: 401

The exception I get for a missing filename is 'OSError', not 'IOError'. And if you get the exception, you just want to pass, and the file writing should be outside the try block.

try:
    os.remove("NumPyResults.txt")
except OSError:
    pass

with open("NumPyResults.txt", 'a') as results_file:
    results_file.write('hi\n')

Upvotes: 12

Related Questions