gpt4 book ai didi

python - rw+ 和 r+ 有什么区别

转载 作者:太空狗 更新时间:2023-10-30 01:32:28 27 4
gpt4 key购买 nike

我在做一些文件 IO 时偶然发现了这个 stackoverflow 问题:Confused by python file mode "w+"

  • r for reading
  • w for writing
  • r+ opens for reading and writing (cannot truncate a file)
  • w+ for writing and reading (can truncate a file)
  • rb+ reading or writing a binary file
  • wb+ writing a binary file
  • a+ opens for appending

请注意 r+ 不能截断文件。所以我正在寻找可以在阅读文件后截断文件的东西,这让我找到了另一个 SO 链接:Python truncate lines as they are read

我看到他们使用了一种不同的模式,rw+,没有记录。从它在答案中的使用方式来看,我猜它的意思是“打开以进行读取、写入和截断,但在打开时不截断”。

我后来测试了这个模式,它似乎在 Python 3 中被删除了,因此在使用时抛出一个 ValueError:

python 2:

f = open("myfile.txt", "rw+")
text = f.read()
f.truncate(0)
f.close()

python 3:

f = open("myfile.txt", "rw+")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: must have exactly one of create/read/write/append mode

但是,我需要 Python 3 中的文件模式,它可以截断和读取但不能在打开时截断。因此,经过更多测试后,我发现 r+ 实际上可以在 Python 2 和 3 中截断。

python 2:

f = open("myfile.txt", "r+")
text = f.read()
f.truncate(0)
f.seek(0, 0)
print f.read()
f.close()

什么都不打印。

python 3:

f = open("myfile.txt", "r+")
text = f.read()
f.truncate(0)
f.seek(0, 0)
print(f.read())
f.close()

也不会打印任何内容。

我的问题是,如果 r+rw+ 都可以截断,它们在 Python 2 中有什么区别?

最佳答案

至少在 Linux 上,据我所知没有区别。这是一个测试脚本

f1 = open('f1', 'r+')
f2 = open('f2', 'rw+')
f3 = open('f3', 'w+')

及其相应的操作系统系统调用(使用 strace);在 python 2.7.9 上测试。

open("f1", O_RDWR|O_LARGEFILE)          = 3
open("f2", O_RDWR|O_LARGEFILE) = 4
open("f3", O_RDWR|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 5

参见 http://man7.org/linux/man-pages/man2/open.2.html有关文件访问和创建标志的更多详细信息。

说用“r+”打开的文件对象不能用于截断文件是不准确的——它只是在文件打开时不这样做。

关于python - rw+ 和 r+ 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41406116/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com