简体   繁体   中英

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. 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. Which means that Python will flush the output to the file (ie do a write operation), for every new-line it finds.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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