954,510 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

with statement not working

According to the Python 2.7 manual this construction of the with statement should work:

text = "aim low and reach it"

fname = "test7.txt"

with open(fname, 'w') as foutp, open(fname, 'r') as finp:
    # write text to file
    foutp.write(text)
    # read text from file
    mytext = finp.read()

print("to file --> %s" % text)
print('-'*30)
print("from file --> %s" % mytext)

""" my result -->
to file --> aim low and reach it
------------------------------
from file --> 
"""


It writes the file out, but does not read it in. There is no error traceback.

HiHe
Posting Whiz in Training
236 posts since Oct 2008
Reputation Points: 137
Solved Threads: 22
 


The result is correct since you open it for reading before anything is written to it.

text = "aim low and reach it"

fname = "test7.txt"
 
with open(fname, 'w') as foutp:
    # write text to file
    foutp.write(text)

# read text from file
with open(fname, 'r') as finp:
    mytext = finp.read()
 
print("to file --> %s" % text)
print('-'*30)
print("from file --> %s" % mytext)
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
 

woooee is on to something, in your case you need to close the file before you can read it ...

text = "aim low and reach it"

fname = "test7.txt"

with open(fname, 'w') as foutp, open(fname, 'r') as finp:
    # write text to file
    foutp.write(text)
    # need to close the outp file so you can read it
    foutp.close()
    # read text from file
    mytext = finp.read()
    #print(foutp, finp)  # test

print("to file --> %s" % text)
print('-'*30)
print("from file --> %s" % mytext)

""" my result -->
to file --> aim low and reach it
------------------------------
from file -->  aim low and reach it 
"""
vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

I think woooee's approach is clearer. The extra close() may be too easy to miss.

bumsfeld
Nearly a Posting Virtuoso
1,445 posts since Jul 2005
Reputation Points: 404
Solved Threads: 184
 
I think woooee's approach is clearer. The extra close() may be too easy to miss.

I agree! I think the OP wanted to explore the fact that can open two files on the same 'with' line.

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: