gpt4 book ai didi

python - 写入文件后无法读取文件

转载 作者:行者123 更新时间:2023-12-01 05:51:35 24 4
gpt4 key购买 nike

我目前正在阅读“艰难地学习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

最佳答案

您没有调用函数 target.closetxt.close,而只是获取它们的指针。由于它们是函数(更准确地说是方法),因此您需要在函数名称后添加 () 来调用它:file.close()

这就是问题所在;您以写入模式打开文件,这会删除文件的所有内容。您在文件中写入但从未关闭它,因此更改永远不会提交并且文件保持为空。接下来,您以读取模式打开它并简单地读取空文件。

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

此外,调用 target.truncate() 是没有用的,因为在 write 模式下打开时它已经自动完成,如评论中所述。

编辑:评论中也提到,使用 with 语句非常强大,您应该使用它。您可以从 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()

关于python - 写入文件后无法读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14100937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com