15

Let's say that I open a file, that didn't previously exist, for writing:

f = open('/tmp/test.txt', 'w')

Once this line is executed the file '/tmp/test.txt' is created. What is the cleanest way to remove (delete) the file with only the file object (f) and not the path?

4 Answers 4

31

You cannot remove a file handle, only a file path, since multiple paths can refer to the same file and some files (like sockets) don't even have paths. Therefore:

import os
f = open('/tmp/test.txt', 'w')
os.unlink(f.name)
# You can still use f here, it's just only visible for people having a handle.
# close it when you're finished.

However, you should not do that - there's a better way to solve your problem. Use the tempfile module which deletes the file automatically, or just write to /dev/null if you just need a file handle and don't care about the content being written.

Sign up to request clarification or add additional context in comments.

Comments

11

Full answer:

f = open('/tmp/test.txt', 'w')
f.close()

os.remove(f.name)

You should close file before deleting (documentation says that it throws exception under Windows if the file is opened - didn't check this). f in your case is just a handle. It is not a file itself, so you can't delete it directly.

Comments

5

You can get the file name from the name member and delete as usual:

In [1]: f = open('/tmp/test.txt', 'w')

In [2]: f.name
Out[2]: '/tmp/test.txt'

Comments

1

Depending on your needs, you could also get away without creating a file at all. If all you need is a file-like object, most of the time you can use an instance of io.StringIO in place of a file. This can be useful to prevent unnecessary i/o operations.

>>> from io import StringIO
>>> f=StringIO()
>>> f.write(u'Hello, world!')
13
>>> f.seek(0)
0
>>> f.read()
u'Hello, world!'
>>> f.close()

Comments

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.