Salı, Mart 04, 2008

Python file handling


From Python documentation:
----------------
write( str)

Write
a string to the file. There is no return value. Due to buffering, the
string may not actually show up in the file until the flush() or
close() method is called.
----------------

Thus flush()
should be used before reading any information just written to a file
moreover seek() should be used to reposition the file pointer thus the code should be changed as follows:

f = open('c:/test.txt','w+') # open file for updating
f.write('Hello World') # write some text to it
f.flush() # flush the internal buffer
f.seek(0) # reposition file pointer to beginning of file This is important when you need to rewind the pointer
f.read() # read the text that was just written

Hiç yorum yok: