how to delete a test file after finished testing in python?

Assuming you're using a unittest-esque framework (i.e. nose, etc.), you would want to use the tearDown method to delete the file, as that will run after each test.

def tearDown(self):
    os.remove('some_file_to_test')

If you want to only delete this file after all the tests, you could create it in the method setUpClass and delete it in the method tearDownClass, which will run before and after all tests have run, respectively.


Other option is to add a function to be called after tearDown() using addCleanup() method of TestCase:

class TestSomething(TestCase):
     def setUp(self):
         # create file
         fo = open('some_file_to_test','w')
         fo.write('write_something')
         fo.close()
         # register remove function
         self.addCleanup(os.remove, 'some_file_to_test')

It is more convenient than tearDown() in cases where there are a lot of files or when they are created with random names because you can add a cleanup method just after file creation.


Write a tearDown method:

https://docs.python.org/3/library/unittest.html#unittest.TestCase.tearDown

def tearDown(self):
    import os
    os.remove('some_file_to_test')

Also have a look at the tempfile module and see if it's useful in this case.