Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
File handling
#1
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?
Reply
#2
I think you're forgetting to call the close function. Replace close with close().
Reply
#3
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())
Reply
#4
Thanks for the replies. problem solved. It was obvious, but I couldn't see it.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  File Handling not working properly TheLummen 8 750 Feb-17-2024, 07:47 PM
Last Post: TheLummen
  file handling Newbee question middlecope 2 783 Jan-18-2023, 03:09 PM
Last Post: middlecope
Star python exception handling handling .... with traceback mg24 3 1,283 Nov-09-2022, 07:29 PM
Last Post: Gribouillis
  File handling issue GiggsB 4 1,442 Mar-31-2022, 09:35 PM
Last Post: GiggsB
  How can I solve this file handling issue? GiggsB 17 3,591 Feb-14-2022, 04:37 AM
Last Post: GiggsB
  How to solve this file handling issue? GiggsB 3 1,701 Jan-10-2022, 09:36 AM
Last Post: Gribouillis
  file handling sivareddy 1 1,642 Feb-23-2020, 07:28 PM
Last Post: jefsummers
  delete file with handling 3Pinter 1 2,106 Oct-17-2019, 04:06 PM
Last Post: 3Pinter
  Help with file handling gonzo620 10 8,387 Sep-27-2018, 06:28 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020