一次又一次地重新打開同一個文件顯然需要更多的時間:
[email protected]:~/Work/playground$ python opentest.py
each :
11.1244959831
once :
0.124312162399
[email protected]:~/Work/playground$ cat opentest.py
def each(data):
for whatever in data:
with open("opentest-each.dat", "a") as f:
f.write(whatever)
def once(data):
with open("opentest-once.dat", "a") as f:
for whatever in data:
f.write(whatever)
def main():
import timeit
t1 = timeit.Timer("each(data)", "from opentest import each; data=map(str, range(10000))")
print "each : "
print t1.timeit(100)
t2 = timeit.Timer("once(data)", "from opentest import once; data=map(str, range(10000))")
print "once : "
print t2.timeit(100)
if __name__ == "__main__":
main()
WRT /內存使用情況,使用with open(...)
不應該讓任何明顯的差異(如果它使在所有的任何區別)。
現在請注意,如果您的代碼需要作爲命令行腳本運行,最好的解決方案是寫入sys.stdout
並使用shell將stdout
重定向到文件。
爲什麼不分析它並找出答案? – jonrsharpe
使用'open..' ususally適合我。您不必擔心關閉它,也無需每次打開它 – user2963623