为什么我不能指定文件的打开方式?(Why can't I specify how a file is opened?)

编程入门 行业动态 更新时间:2024-10-27 15:22:02
为什么我不能指定文件的打开方式?(Why can't I specify how a file is opened?)

请考虑以下代码:

try: f = open("myfile2.dat", "rb") except IOError: f = open("myfile2.dat", "ab+") print(f.mode) f.close()

如果我在运行此代码时myfile2.dat不存在,则Idle打开一个rb +而不是ab +的新文件,为什么?

Consider the following code:

try: f = open("myfile2.dat", "rb") except IOError: f = open("myfile2.dat", "ab+") print(f.mode) f.close()

If myfile2.dat doesn't exist when I run this code Idle opens a new file with rb+ not ab+, why?

最满意答案

您正在追加+写入模式下打开一个文件。 因为没有要附加的文件,所以您可以使用读取+写入模式。

基本上是一回事。 这里没有问题,你仍然可以读取写入文件。

在引擎盖下,文件仍以追加模式打开,但.mode属性为文件提供了更简单的视图; 它只会报告您现在可以对文件执行的操作,而不会报告打开文件时发生的情况。 它仅显示您是否可以读取或写入文件以及文件是否已打开以进行独占创建( x模式)。

请参阅.mode属性的C代码 。

更新 :是的,这是令人困惑的,真的是一个错误。 修复这种差异的路径最近已合并到Python中,当Python 2.7,3.3和3.4的新版本出来时,文件对象的.mode属性将更好地反映用于打开文件的原始模式字符串。

You are opening a new file in append + write mode. Because there is no file to append to, you get one in read + write mode instead.

This is essentially the same thing. There is no problem here, you can still both read from and write to the file.

Under the hood, the file is still open in append mode, but the .mode attribute gives a simpler view on the file; it merely will report what you can do with the file now, not what happened when you opened the file. It shows only if you can read or write the file and if the file was opened for exclusive creating (x mode).

See the C code for the .mode attribute.

Update: Yes, this is confusing, and really a bug. The path to fix this discrepancy has recently been merged into Python, and when new releases of Python 2.7, 3.3 and 3.4 come out file objects' .mode attribute will better reflect the original mode string used to open the file.

更多推荐

本文发布于:2023-07-22 19:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1222714.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方式   文件   opened   file

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!