我在做一些文件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 "", line 1, in
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+')
及其相应的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
用’r’打开的文件对象不能用于截断文件是不准确的 – 它只是在文件打开时不这样做.
标签:python,file-io,python-3-x,python-2-x
来源: https://codeday.me/bug/20190710/1428904.html