appeding string to file

Brian Lee senux at senux.com
Thu Apr 11 08:33:14 EDT 2002


I tried follow test code to append string to a file. 
When list t is size 10000, second time is slower fourth
But list t is size 30000, second time is slower twenty three
times than first time.

Why does second test is more slower? Is the load to copy
string to a variable too high?

Any advice?

from Python newbie...

#!/usr/bin/env python

import time
import os

try:
    os.remove('test1.log')
except:
    pass    
try:
    os.remove('test2.log')
except:
    pass    

# prepare
t = []
for x in range(30000):
    t.append('Test string (' + str(x) + ')')
print 'Completed string t'

# first
start = time.time()
for x in t: 
    open('test1.log', 'a').write(x + '\n') 
stop = time.time()
print 'First test:', float(stop - start)

tt = ''
# second
start = time.time()
for x in t: 
    tt += x + '\n'
print 'start writing...'
open('test2.log', 'w').write(tt)
stop = time.time()
print 'Second test:', float(stop - start)

'''
RESULT:

[senux at porsche test]$ python2 write.py 
Completed string t
First test: 1.02917897701
start writing...
Second test: 4.56314098835
[senux at porsche test]$ python2 write.py 
Completed string t
First test: 3.14635396004
start writing...
Second test: 71.6274340153
'''

-- 
 ____       
 |o | i   / Brian Lee    <senux at senux.com>
 #######|<  Web - http://www.senux.com/en/
(x-x-x-x) \ GnuPG public key - 0x46C763A3





More information about the Python-list mailing list