while iter < 10:
//do some things(actual code is too long to post)
iter += 1
for line in code.splitlines():
file = open("tile.txt", "w+")
file.write(line)
print(" "+line)
我在结尾处有这个for循环,当我将变量“line”打印到命令行时,它完美地工作。但是我想在while循环的每次迭代中将“line”的所有值写入文件。我现在的问题是,它只在最后一次迭代中写出了line的值。有什么帮助吗?
答案 0 :(得分:2)
您应该以追加模式打开文件。另外,作为处理文件的更加pythonic方式,最好使用with
语句打开文件,这将在块结束时关闭文件:
with open("tile.txt", "a+") as f:
for line in code.splitlines():
f.write(line + '\n') # Add new line at the end of each line
print(" "+line)
您也可以使用file.writelines()
方法一次在文件中写入多行,但在这种情况下,您仍然可以使用w+
模式。
答案 1 :(得分:1)
你应该在循环外打开文件一次:
file = open("tile.txt", "w+")
while iter < 10:
//do some things(actual code is too long to post)
iter += 1
for line in code.splitlines():
file.write(line)
print(" "+line)
答案 2 :(得分:1)
每当你通过该行时,它会覆盖你写的前一个值,而不是添加到它:
file = open("tile.txt", "w+")
for line in code.splitlines():
file.write(line)
print(" "+line)
上面的代码应该为您提供所有行。它打开文件并在循环内部,所有值都写入文件。在循环结束后,您应该关闭文件以获得结果。
file.close()