Opening & closing file using file object:
fp=open("ram.txt","w")
fp.close()
If we want to Open & close file without using file object ,i.e;
open("ram.txt","w")
Do we need to write close("poem.txt")
or writing close()
is fine?
None of them are giving any error...
By only writing close() ,How it would understand to what file we are referencing?
Definition of opening 1a : an act or instance of making or becoming open. b : an act or instance of beginning : commencement especially : a formal and usually public event by which something new is put officially into operation. 2 : something that is open: such as.
spread (out), stretch (out), unfold, unfurl.
opening-up noun - Definition, pictures, pronunciation and usage notes | Oxford Advanced Learner's Dictionary at OxfordLearnersDictionaries.com.
Opening can be an adjective, a verb or a noun.
For every object in memory, Python keeps a reference count. As long as there are no more references to an object around, it will be garbage collected.
The open()
function returns a file object.
f = open("myfile.txt", "w")
And in the line above, you keep a reference to the object around in the variable f
, and therefore the file object keeps existing. If you do
del f
Then the file object has no references anymore, and will be cleaned up. It'll be closed in the process, but that can take a little while which is why it's better to use the with
construct.
However, if you just do:
open("myfile.txt")
Then the file object is created and immediately discarded again, because there are no references to it. It's gone, and closed. You can't close it anymore, because you can't say what exactly you want to close.
open("myfile.txt", "r").readlines()
To evaluate this whole expression, first open
is called, which returns a file object, and then the method readlines
is called on that. Then the result of that is returned. As there are now no references to the file object, it is immediately discarded again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With