4

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'
Renae Lider
  • 1,004
  • 7
  • 20
cc6g11
  • 477
  • 2
  • 10
  • 24

1 Answers1

12

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')
dethtron5000
  • 10,363
  • 1
  • 31
  • 32
Robert E
  • 413
  • 4
  • 7