Delete the file if it exists. If not, create it

The name says it 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 this is happening is because it is in a function and called many times. So every time I run the program, I want a new file, deleting the old one and writing the new one.

However, this does not create a new file. I also created a file in the directory I am running in and it also does not delete it.

I get

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

      

+3


source to share


1 answer


The exception I get for the missing filename is "OSError", not "IOError". And if you get an exception, you just want to pass and the file entry must 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')

      

+6


source







All Articles