![](/img/trans.png)
[英]Is there a more efficient way than this way of if statements in python?
[英]Is it more efficient to write to a file in one statement than multiple statements?
我正在运行的循环将大约10000行写入文件。 我一直在搜索,但找不到在写入语句中连接字符串或使用多个写入语句是否更有效。 即:
f = open(fileName,"w+")
for item in list:
f.write(str1 + str2 + str3 + item + "\n\n")
要么
f = open(fileName,"w+")
for item in list:
f.write(str1)
f.write(str2)
f.write(str3)
f.write(item)
f.write("\n\n")
第一种或第二种选择是否更有效率?
我想这以前曾被问过,我以一种奇怪的方式问这个问题,所以如果有人能指出我正确的方向,那就太好了!
当未指定缓冲模式时, open
方法的默认行为是遵循通常是行缓冲的系统默认值。 这意味着Python将针对找到的每行换行将输出刷新到文件(即执行写操作)。
因此,在此示例中,我认为,就文件IO性能而言,这两个操作是等效的,因为换行符是最后输出的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.