打开(文件,“wt”或“rt”)不同的对象? [英] Are open(file, "wt" or "rt") different objects?

查看:242
本文介绍了打开(文件,“wt”或“rt”)不同的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  file = open(my file,wt)
code>

  file =打开(我的文件,rt)

这些都创建文件对象,我们使用文件方法上。但他们创造不同的文件对象?如果他们正在创建不同的文件对象,可以公平地说,wt一个是可变的,而rt一个是不可变的?

解决方案不,这样说不公平。您正在创建相同标准的文件类型的实例,该文件将文件操作调用代理到操作系统。该模式定义了操作系统允许你做的事情。



不管你使用相同的文件名还是不同的文件名,操作系统不在乎,Python也不在乎;打开的文件对象是不同的。



Python对象本身是不可变的;请注意,通过在模式中添加 + ,您不能改变模式,文件名或其他属性。

,你可以读取写入文件对象; w + 会先截取文件,而 r + 不会。


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?

解决方案

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.

这篇关于打开(文件,“wt”或“rt”)不同的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆