Python Forum

Full Version: File handling
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Although I have been programming since 1956, I can't get beyond simple things in Python, in particular, getting data into and out of files.
I opened a file ('a'), and wrote 2 lines in it, acknowledged by the character count.
Closed it, opened it to read, but reading produces blank output:

tf = open('testfile.txt', 'a')
tf.write('line1')
tf.write('line2')
tf.close
tg = open('testfile.txt', 'r')
print(tg.read())
tg.close 
The print command gives me a blank line. What am I doing wrong?
I think you're forgetting to call the close function. Replace close with close().
Also using with open which is the preferable way now,then no need to use close().
It's not so new as with open was added to Python 2.5 14-years ago Wink
Here in all in one go.
with open('testfile.txt', 'a') as tf, open('testfile.txt') as tg:
    tf.write('line1\n')
    tf.write('line2\n')
    print(tg.read())
Or:
with open('testfile.txt', 'a') as tf:
    tf.write('line1\n')
    tf.write('line2\n')

with open('testfile.txt') as tg:
    print(tg.read())
Thanks for the replies. problem solved. It was obvious, but I couldn't see it.