正确理解Python文件读写模式字w+、a+和r+

时间:2023-03-08 20:04:31
w+ 和 r+的差别不难理解。还有a+

+同一时候读写,就可以读又可写,边写边读、边读边写,不用flush,用seek 和 tell可測得。

fp = open("a.txt", "a+", 0)
print 'open',fp.tell()
x = fp.read()
print 'open read()',fp.tell()
print x
fp.write("123456\n")
print 'write 1-6',fp.tell()
x = fp.read()
print "first read\n",x
fp.seek(0)
x = fp.read()
print "second read\n", x,fp.tell()
fp.close()

第一次执行时的结果是:

open 0
open read() 0 write 1-6 8
first read second read
123456
8

第二次执行时的结果是

open 0
open read() 8
123456 write 1-6 16
first read second read
123456
123456
16