加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – rw和r有什么区别

发布时间:2020-12-20 13:15:41 所属栏目:Python 来源:网络整理
导读:我在做一些文件IO: Confused by python file mode “w+”时偶然发现了这个stackoverflow问题 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 w
我在做一些文件IO: Confused by python file mode “w+”时偶然发现了这个stackoverflow问题

  • 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",0)
print(f.read())
f.close()

还会打印出来.

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

解决方法

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

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

及其相应的OS系统调用(使用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’打开的文件对象不能用于截断文件是不准确的 – 它只是在文件打开时不这样做.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读