简体   繁体   English

读/写文件:“a”比“a+”模式快吗?

[英]Reading/writing files: Is "a" faster than "a+" mode?

Based on many people's answer, it looks the only difference between "a" and "a+" mode is that "a+" is not only write/append, but also "read".根据很多人的回答,看起来“a”和“a+”模式之间的唯一区别是“a+”不仅是写/追加,而且是“读”。

From my using file open experience, without "a+" mode, I can do write append with "a" pretty well.从我使用文件打开的经验来看,没有“a+”模式,我可以很好地用“a”写附加。 Does "a" give me performance improvement if I don't need read for the file at all?如果我根本不需要读取文件,“a”是否可以提高我的性能?

For example:例如:

with open('file.txt', 'a') as f:
    f.write('line\n');

If you run this test on identical text files, the loop using 'a+' runs about one one hundredth of a second slower that 'a'.如果您在相同的文本文件上运行此测试,则使用“a+”的循环运行速度比“a”慢约百分之一秒。 This difference does not change significantly as the test is repeated and the files continue to grow larger and larger.随着测试的重复和文件继续变得越来越大,这种差异不会显着改变。 This would indicate that even though 'a+' is very slightly slower, it does not seem to spend any extra time reading the file first.这表明即使 '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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM