简体   繁体   English

为什么python文件描述符“ w +”用于读取时会擦除文件内容?

[英]Why does the python file descriptor 'w+' erase the contents of file when used for reading?

contents of foo.txt foo.txt内容

Hello World!

Two functions : 两个functions

def read1(file):
    with open(file, 'r+') as fp:
        print fp.read()

def read2(file):
    with open(file, 'w+') as fp:
        print fp.read()

the function read1('foo.txt') outputs: Hello World! 函数read1('foo.txt')输出: Hello World!

the function read2('foo.txt') outputs: 函数read2('foo.txt')输出:

It essentially outputs nothing. 它基本上什么也不输出。 But why? 但为什么?

Not only that, the contents of foo.txt has been erased as well. 不仅如此, foo.txt的内容也已被删除。

I thought that w+ means you truncate the file, meaning you write over it. 我认为w+意味着您截断了文件,这意味着您将其覆盖。 But I did not even use fp.write() . 但是我什fp.write()没有使用fp.write()

"Truncate the file" does not mean writing over existing contents (but leaving that content present until it's overwritten); “截断文件”并不意味着覆盖现有内容(而是保留该内容直到被覆盖); rather, it means entirely removing everything past the point at which the file is truncated. 相反,它意味着完全删除文件被截断后的所有内容。 In this case, that point is the very beginning of the file. 在这种情况下,这就是文件的开头。

If you want to open the file and be able to read existing contents before performing an in-place write over any subset, r+ is the appropriate mode. 如果要打开文件并能够在对任何子集执行就地写入之前读取现有内容,则r+是合适的模式。


Quoting a definition of "truncate" from WordNet 3.0, to "truncate" something is to cut it off, or cut it short: 引用WordNet 3.0中“截断”的定义来“截断”某些内容是为了将其截断或缩短:

truncate 截短

3: make shorter as if by cutting off; 3:通过剪短使其变短; "truncate a word"; “删减一个词”; "Erosion has truncated the ridges of the mountains" [syn: truncate, cut short] “侵蚀把山的山脊截断了” [syn:截短,剪短]

Thus, the name matches well with the behavior at hand. 因此,该名称与当前的行为非常匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM