-1

I'm writing some test cases and I want to create a temporary csv file and remove it after the test completes. For some reason, the file persists.

I was under the impression that the file only exists for the duration of the with scope. Also, am I able to access the file with the rows I have just written within the same scope?

Here is what I have so far.

    with open('test.csv', 'w') as file:
        writer = csv.writer(file)
        writer.writerows(row_list)
        return handle_upload_file(file)

My handle_upload_file just reads the data from a csv file. Could it be that the function is erroring out because the file is not in the correct format causing the file to never be deleted after?

Eric Svitok
  • 792
  • 5
  • 11
  • Does this answer your question? [How can I create a tmp file in Python?](https://stackoverflow.com/questions/8577137/how-can-i-create-a-tmp-file-in-python) OR [create temporary file in python that will be deleted automatically after sometime](https://stackoverflow.com/questions/44798879/create-temporary-file-in-python-that-will-be-deleted-automatically-after-sometim) – Tomerikoo Nov 04 '20 at 15:43

2 Answers2

0

Once you leave the scope, the file will be closed, not deleted. You will need to delete the file explicitly afterwards, eg. using https://docs.python.org/3/library/os.html#os.unlink:

with open('test.csv', 'w') as file:
    # whatever you need to do
    pass
os.unlink('test.csv')

You might be looking for something like https://docs.python.org/3/library/tempfile.html, by the way; see https://stackoverflow.com/a/8577226/1683161.

rainer
  • 6,769
  • 3
  • 23
  • 37
0

File is closed but not deleted. You have to delete it manually.

os.remove("test.csv")
zvi
  • 3,677
  • 2
  • 30
  • 48