Are open(file, “wt” or “rt”) different objects?

耗尽温柔 提交于 2020-01-15 05:29:07

问题


When you do:

file = open("my file","wt")

and

file = open("my file" , "rt")

These both create file objects that we use file methods on. But are they creating different file objects? And if they are creating different file objects would it be fair to say that the "wt" one is mutable, while the "rt" one is immutable?


回答1:


No, that would not be fair to say. You are creating instances of the same standard file type, which proxies file manipulation calls to the operating system. The mode defines what the operating system will let you do.

It doesn't matter if you use the same filename or different filenames; the OS doesn't care, and neither does Python; the open file objects are distinct.

The Python object itself is immutable; you cannot change the mode, filename or other attributes after the fact.

Note that by adding + to the mode, you can both read and write to the file object; w+ will truncate the file first, while r+ would not.




回答2:


At the OS level, they would be created as two distinct file descriptors. They would (likely) point to the same data in the VFS/cache, but can be operated independently.



来源:https://stackoverflow.com/questions/17127853/are-openfile-wt-or-rt-different-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!