jab
jab

Reputation: 5823

Simple Python File/Object Instance

Let's say I have the following code,

file1 = open("myfile","w")

#Write to file1...

#Open Second File
file2 = open("otherfile","w")

#Write to file2...

file1.close()

file1 = file2

file2.close()

Will this effectively result in all files being closed or will file1 still have an open file (otherfile) that can be written to still?

Upvotes: 0

Views: 152

Answers (3)

user104365
user104365

Reputation:

since you closed file1 before you re-assigned it, both files are closed

Upvotes: 0

Joel Cornett
Joel Cornett

Reputation: 24788

Yes. (To clarify, both file objects will be closed, and will not be able to be written to) The variable names are just references to the underlying objects. When you call the close() method on an object, it accesses that object and executes that method. If you examine both objects afterwards, you can tell:

>>> file1
<closed file 'file2.txt', mode 'w' at 0x10045e930>
>>> file2
<closed file 'file2.txt', mode 'w' at 0x10045e930>
>>> 

Note that in this situation, you set file1 = file2 so they both refer to the same closed file object. If there are no more references to the original file1 object, that object will be garbage collected.

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599610

No, by your second-last line both file1 and file2 refer to the same file object, which is closed by file2.close(). Python variables are just names pointing to objects, so what you do to one name happens to all names pointing at that object.

Upvotes: 1

Related Questions