Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

opening & closing file without file object in python

Tags:

python

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?

like image 495
user3223301 Avatar asked Feb 27 '14 13:02

user3223301


People also ask

What is the mean of opening?

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.

What is the synonym of opening?

spread (out), stretch (out), unfold, unfurl.

How do you spell opening up?

opening-up noun - Definition, pictures, pronunciation and usage notes | Oxford Advanced Learner's Dictionary at OxfordLearnersDictionaries.com.

What type of word is opening?

Opening can be an adjective, a verb or a noun.


1 Answers

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.

like image 171
RemcoGerlich Avatar answered Sep 22 '22 19:09

RemcoGerlich