Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - Cannot read file after writing to it

I am currently reading "Learn Python the hard way" and have reached chapter 16.
I can't seem to print the contents of the file after writing to it. It simply prints nothing.

from sys import argv

script, filename = argv print "We are going to erase the contents of %s" % filename print "If you don't want that to happen press Ctrl-C" 
print "If you want to continue press enter"

raw_input("?") print "Opening the file..." target = open(filename, "w")

print "Truncating the file..." target.truncate()

print "Now i am going to ask you for 3 lines"

line_1 = raw_input("Line 1: ") 
line_2 = raw_input("Line 2: ") 
line_3 = raw_input("Line 3: ") 

final_write = line_1 + "
" + line_2 + "
" + line_3

print "Now I am going to write the lines to %s" % filename

target.write(final_write)

target.close

print "This is what %s look like now" %filename

txt = open(filename)

x = txt.read() # problem happens here 
print x

print "Now closing file"

txt.close
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're not calling functions target.close and txt.close, instead you're simply getting their pointers. Since they are functions (or methods, to be more accurate) you need () after the function's name to call it: file.close().

That's the problem; you open the file in write mode which deletes all the content of the file. You write in the file but you never close it, so the changes are never committed and the file stays empty. Next you open it in read mode and simply read the empty file.

To commit the changes manually, use file.flush(). Or simply close the file and it will be flushed automatically.

Also, calling target.truncate() is useless, since it's already done automatically when opening in write mode, as mentioned in the comments.

Edit: Also mentioned in the comments, using with statement is quite powerful and you should use it instead. You can read more of with from http://www.python.org/dev/peps/pep-0343/, but basically when used with files, it opens the file and automatically closes it once you unindent. This way you don't have to worry about closing the file, and it looks much better when you can clearly see where the file is being used, thanks to the indentation.

Quick example:

f = open("test.txt", "r")
s = f.read()
f.close()

Can be done shorter and better looking by using with statement:

with open("test.txt", "r") as f:
    s = f.read()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...