gpt4 book ai didi

python文件读取()显示空行

转载 作者:太空宇宙 更新时间:2023-11-04 01:20:36 25 4
gpt4 key购买 nike

我正在在线学习一系列教程 (http://learnpythonthehardway.org/book/ex16.html),但我完全被卡住了。我到处寻找答案,但似乎无法找到解决方案。如果这是一个愚蠢的问题并且非常明显,我深表歉意,但我是一个初学者。

除了一个错误,下面的脚本工作正常。当脚本运行时,第 29 行的 .read() 命令返回空。

如果有人能告诉我这是为什么以及我该如何解决它,我将非常高兴。

亲切的问候。 :)

from sys import argv

script, filename = argv

print "we are going to erase the %r" % filename
print "if you do not want to do that hit ctrl C ( ^c )."
print "if you do want to do that hit return."

raw_input ("?")

print "opening the file....."
target = open (filename, "r+")

print "truncating the file. goodbye!"
target.truncate ()

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

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

print "now, im going to write those 3 lines to the %s file:" % filename

target.write ("%s\n%s\n%s" % (line1, line2, line3))

print "now i am going to show you the contents of the file:"

print target.read()


print "and finally we close."
target.close()

最佳答案

文件光标已移动到您的写入之后。这是写作的自然结果。如果你想阅读你写的内容,你需要将文件光标重置回文件的开头:

target.seek(0)

...后续读取现在可以访问您放入文件中的文本。

关于python文件读取()显示空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21489738/

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