写入文件后无法读取文件

发布于 2021-01-29 14:59:51

我目前正在阅读“用困难的方式学习Python”,已经读到了第16章。
写入文件后,似乎无法打印文件的内容。它只是不打印任何内容。

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 + "\n" + line_2 + "\n" + 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
关注者
0
被浏览
85
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    你不调用函数target.closetxt.close,而不是你只是得到他们的 指点
    。由于它们是函数(或更准确地说,是方法),因此您需要()在函数名称后调用它:file.close()

    那就是问题所在;
    您以写入模式打开文件,该模式将删除文件的所有内容。您写入了文件,但从未关闭它,因此更改从未提交,文件保持为空。接下来,您以读取模式打开它,只需读取空文件。

    要手动提交更改,请使用file.flush()。或者直接关闭文件,它将自动刷新。

    同样,调用target.truncate()是无用的,因为write如注释中所述,以模式打开时它已经自动完成。

    编辑
    :在注释中也提到过,usingwith语句功能非常强大,您应该改用它。您可以从http://www.python.org/dev/peps/pep-0343/中阅读更多内容,但是基本上,当与文件一起使用时,它会打开文件并在您取消缩进后自动关闭它。这样,您不必担心关闭文件,由于缩进,当您可以清楚地看到文件的使用位置时,它看起来要好得多。

    快速示例:

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

    可以通过使用以下with语句来做得更短,更好看:

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看