Delete file with python file only

Let's say that I open a file that did not previously exist for writing:

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

After executing this line, the file '/tmp/test.txt' is created. What is the cleanest way to delete (delete) a file with only the file (f) and not with the path?

+6
source share
4 answers

You cannot delete the file descriptor, only the file path, since several paths can refer to the same file and some files (for example, sockets) do not even have paths. Therefore:

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

However, you should not do this - there is a better way to solve your problem. Use the tempfile module, which automatically deletes the file or simply writes to /dev/null if you just need a file descriptor and don't care about the written content.

+19
source

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' 
+4
source

Full answer:

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

Before deleting, close the file (the documentation says that it throws an exception under Windows; if the file is open, it did not check this). f in your case, it's just a pen. This is not a file, so you cannot delete it directly.

+2
source

Depending on your needs, you can also leave without creating a file at all. If you need a file-like object, most of the time you can use an io.StringIO instance instead of a file. This can be useful to prevent unnecessary I / O.

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

Source: https://habr.com/ru/post/899783/


All Articles