首页 > python read()的问题

python read()的问题

我在敲《笨办法学python》这本书时遇到的问题,习题16。
我的代码如下:

from sys import argv

script, filename = argv

print "We're going to rease %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w+')

print "Trincating the file. Goodbye!"

target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print "Here's your file %r:" % filename
print target.read()

print "And finally, we close it."
target.close()

结果如下:

我就想在写完文件后,再看下文件的内容。
但是并没有读取新文件,还出现了奇怪的东西。
请问我的代码问题出现在哪了?


很简单,出于性能方面的考虑,你往文件写入并不是实时写入的,而是写入缓冲区的,在你没有flush或者close之前,都还没有真正进入文件
详见python文档
https://docs.python.org/2/library/stdtypes.html?highlight=write#file.write

然后还有一个问题是你文件是使用写模式打开的,你需要改成r+才可以同时支持读写,也就是
target = open(filename, 'r+')

(修正: r+和w+和a+都可以读写文件,其中w+会清空原始存在的文件,见:https://docs.python.org/2/library/functions.html?highlight=open#open)

你需要在你的read之前加上这两行代码:

target.flush() #写入数据,清空缓冲区
target.seek(0) #把文件指针归零
【热门文章】
【热门文章】