Reputation: 641
I have a simple block of code that opens a file then after running through a for
loop it closes the file.
However it doesn't seem to release the file because the following line underneath the loop and close
print os.stat('/root/message').st_size
shows as 0
. If I do an ls -l
it shows the filesize and I can cat
the file out and it has the correct contents.
Here's the code block.
#!/usr/bin/python
import os
objects = { 'dave' : 'builder' , 'fred' : 'cobbler' , 'frank' : 'shoplifter' }
log = open('/root/jam' , 'w')
for bloke in objects:
log.write("%s is a %s \n" % (bloke, objects[bloke]))
log.close
print os.stat('/root/jam').st_size
What am I doing wrong here?
Upvotes: 1
Views: 70
Reputation: 2781
Don't know what is the issue with write mode but it can be done using 'r+'.
import os
objects = { 'dave' : 'builder' , 'fred' : 'cobbler' , 'frank' : 'shoplifter' }
log = open('jam.txt', 'r+')
for bloke in objects:
log.write("%s is a %s \n" % (bloke, objects[bloke]))
log.close()
print os.stat('jam.txt').st_size
Other modes can be seen on http://www.tutorialspoint.com/python/python_files_io.htm
Upvotes: 0
Reputation: 1121316
You forgot to call the file.close
method; add ()
to not just reference the method but actually invoke it:
log.close()
Python otherwise would auto-close the file as soon as your script ends, which is why the ls -l
and cat
commands show you a size and the file contents.
You could also use the file object as a context manager, using the with
statement; as soon as the with
block ends the file will be closed for you:
import os
objects = { 'dave' : 'builder' , 'fred' : 'cobbler' , 'frank' : 'shoplifter' }
with open('/root/jam' , 'w') as log:
for bloke in objects:
log.write("%s is a %s \n" % (bloke, objects[bloke]))
# with block ends, file is closed for you
print os.stat('/root/jam').st_size
Upvotes: 6