输出新行到txt文件。 (Python 3.2)

时间:2011-05-19 01:28:51

标签: python text

所有。我在将新行输出到txt文件时遇到问题。输出很好,但它只是一行。关于如何解决的任何想法?

#Double numberer
end=100
count=0

count=int(input("What number would you like to start?"))
end=int(input("What number would you like to end?"))
biglist = []

logfile=open("output.txt", mode="w", encoding="utf-8")

while count < end+1:
    logfile.write(str(count),"\n")
    logfile.write(str(count),"\n")
    print(count)
    count += 1


print("done")
logfile.close()

2 个答案:

答案 0 :(得分:3)

要将新行连接到字符串,请使用+符号:

logfile.write(str(count) + "\n")
logfile.write(str(count) + "\n")

另外,请注意,Python中每次while循环递增count是不必要的。你可以这样做:

for x in range(0, end + 1):
    logfile.write((str(x) + "\n") * 2)
    print(x)

答案 1 :(得分:1)

一种简单的方法是:

print(string, file=theFileYouOpened)