简体   繁体   English

在一个语句中写入文件是否比多个语句更有效?

[英]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.

相关问题 在python中有没有比这种if语句更有效的方法? - Is there a more efficient way than this way of if statements in python? 有没有比多个 FOR 循环和 IF 语句更有效的方法? - Is there a more efficient way instead of multiple FOR loops and IF statements? 一个条件语句中多个“或”语句的有效方法 - Efficient approach for multiple 'or' statements in an conditional statement 在条件语句中使用 arrays 是否有更短和/或更有效的方法? (在这种情况下是“if”语句) - Is there a shorter and/or more efficient way to utilize arrays in conditional statements? (in this case the “if” statement) 如何在文本文件-Python中编写多个变量? - How to write more than one variable in a text file - Python? 有没有其他方法可以使用多个 arguments 写入文件? - Is there any other way to write into a file using more than one arguments? 如何编写多列的 csv 文件 - How to write a csv file with more than one column 如何在Python中按顺序向文件写入多行 - How to write more than one line to a file sequentially in Python 如何在 Python 中以更有效的方式编写所有这些逻辑语句? - How to write all those logical statements in a more efficient way in Python? 为什么一种方法比另一种方法更有效? - Why is one way more efficient than another?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM