根据许多人的回答,看起来“ a”和“ a +”模式之间的唯一区别是“ a +”不仅是写/追加,而且是“读”。
根据我使用文件打开的经验,没有“ a +”模式,我可以用“ a”编写附加文件。如果我根本不需要读取文件,“ a”是否可以提高我的性能?
例如:
with open('file.txt', 'a') as f:
f.write('line\n');
[如果您在相同的文本文件上运行此测试,则使用'a +'的循环会比'a'慢约百分之一秒。随着测试的重复和文件的不断增加,这种差异不会显着变化。这表明即使'a +'的速度稍微慢一点,它似乎也不会花费额外的时间先读取文件。
from time import time
start = time ()
with open ('testfile1.txt', 'a') as file :
for index in range (9999) :
file.write ('This is a test to see how long this will take.\n')
stop = time ()
first_total = stop - start
start = time ()
with open ('testfile2.txt', 'a+') as file :
for index in range (9999) :
file.write ('This is a test to see how long this will take.\n')
stop = time ()
second_total = stop - start
print ('First = ', first_total)
print ('Second = ', second_total)
print ('Differenct = ', second_total - first_total)