Leto Atreides
Leto Atreides

Reputation: 27

Delete a temporal file when it is closed in Python

I have a function similar to this:

def open_tmp():
    tmp = mktemp()
    copy('file.txt', tmp)
    return open(tmp, 'rt')

And I would like to remove automatically the created temporal file when the file will close, for example:

file = open_tmp()
# Do something with file
file.close()  # I want to remove the temporal file here

Is it possible? I thought to create a subclass of BaseIO and rewrite the close() function, but I think it is too much work because I would have to rewrite all the BaseIO methods.

Upvotes: 0

Views: 174

Answers (2)

Leto Atreides
Leto Atreides

Reputation: 27

I've found the solution:

import os
import tempfile

def open_tmp():
    tmp = tempfile.mkstemp()
    copy('file.txt', tmp)  # This copy the file.txt to tmp
    file = open(tmp, 'rt')
    old_close = file.close
    
    def close():
       old_close()
       os.remove(tmp)

    file.close = close
    return file

Upvotes: 1

Sabil
Sabil

Reputation: 4510

You can try this code snippet. As per security concern I recommended to use tempfile instead of your code.

import os
import tempfile

new_file, file_path = tempfile.mkstemp()

try:
    with os.fdopen(new_file, 'w') as temp_file:
        # Do something with file
        temp_file.write('write some dumy text in file')

finally:
    os.remove(file_path)

Upvotes: 1

Related Questions