我有一些Python代码,如下所示:
try:
f = open("stuff.txt", "w")
f.write("Hello 1.\n")
f.write("How are you? 2.\n")
f.write("Goodbye 3.\n"
f.close()
except IOError:
print "Error Message."
<A lot more Python code here ...>
然而,发生的事情是它写入stuff.txt很好,但它在第一次write()调用后立即停止。所以,stuff.txt,如果你打开它,将包含:
Hello 1.
另一件奇怪的事情是我的所有代码都在第一次调用write()之后(这些东西从未执行过,好像Python脚本刚刚终止,并且第一次写入()。
如何阻止它像这样终止?
此外,以这种方式写入文本文件中的多行是否有意义?所需的输出是(在stuff.txt中):
Hello 1.
How are you? 2.
Goodbye 3.
非常感谢。
答案 0 :(得分:1)
除了)
f.write("Goodbye 3.\n"
外,此代码没有任何问题
>>> def test():
... try:
... f = open("stuff.txt", "w")
... f.write("Hello 1.\n")
... f.write("How are you? 2.\n")
... f.write("Goodbye 3.\n")
... f.close()
... except IOError:
... print "Error Message."
... print "Outside Try -- Catch. This works fine"
...
>>> test()
Outside Try -- Catch. This works fine
答案 1 :(得分:0)
您错过了一个结束语,所以每次都会出错,您应该使用with
打开文件:
with open("stuff.txt", "w") as f: # closes your file automatically
f.write("Hello 1.\n")
f.write("How are you? 2.\n")
f.write("Goodbye 3.\n") # missing closing paren