[英]Is it more efficient to write to a file in one statement than multiple statements?
I'm running loop that writes around 10000 lines to a file. 我正在运行的循环将大约10000行写入文件。 I've been searching but can't find whether it's more efficient to concatenate a string in a write statement, or use multiple write statements.
我一直在搜索,但找不到在写入语句中连接字符串或使用多个写入语句是否更有效。 ie:
即:
f = open(fileName,"w+")
for item in list:
f.write(str1 + str2 + str3 + item + "\n\n")
or 要么
f = open(fileName,"w+")
for item in list:
f.write(str1)
f.write(str2)
f.write(str3)
f.write(item)
f.write("\n\n")
Is the first or second option more efficient? 第一种或第二种选择是否更有效率?
I imagine this has been asked before and I'm asking the question in a strange way, so if someone can point me in the right direction that'd be fantastic! 我想这以前曾被问过,我以一种奇怪的方式问这个问题,所以如果有人能指出我正确的方向,那就太好了!
The default behaviour for the open
method, when not specifying a buffering mode, is to follow the system default which is usually line-buffered. 当未指定缓冲模式时,
open
方法的默认行为是遵循通常是行缓冲的系统默认值。 Which means that Python will flush the output to the file (ie do a write operation), for every new-line it finds. 这意味着Python将针对找到的每行换行将输出刷新到文件(即执行写操作)。
So I would presume in this example that both operations, as far as file IO performance is concerned, are equivalent, seeing as the new-line character is the last thing output. 因此,在此示例中,我认为,就文件IO性能而言,这两个操作是等效的,因为换行符是最后输出的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.