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'
4
  • 3
    stackoverflow.com/questions/2967194/… Commented Aug 7, 2015 at 15:40
  • 2
    append doesn't remove the file by definition Commented Aug 7, 2015 at 15:44
  • 3
    Why not just use open(path, 'w')? It deletes the old file and rewrites over it. Commented Aug 7, 2015 at 15:46
  • 1
    All this is inside a function? Won't the file get deleted each time you make a call? Commented Aug 7, 2015 at 15:48

1 Answer 1

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')
Sign up to request clarification or add additional context in comments.

1 Comment

For what it's worth, I get FileNotFoundError on python3.4 and OSError on python2.7

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.