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?
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:Note that in this situation, you set
file1 = file2so they both refer to the same closed file object. If there are no more references to the originalfile1object, that object will be garbage collected.