0

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?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.