2011-05-19 66 views
0

全部。我无法将新行输出到txt文件。输出很好,但都在一条线上。任何想法如何解决?输出新行到txt文件。 (Python 3.2)

#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() 
+1

请粘贴您的代码在这里,而在一些其他的网站。 StackOverflow在这里是一个高质量问题和答案的仓库;当pastebin关闭他们的门或过期时会发生什么?这将变得(更)无用,对未来的其他人没有任何帮助。感谢他们的大门或过期的旧帖子?这将变得(更)无用,对未来的其他人没有任何帮助。谢谢! – sarnold 2011-05-19 01:31:49

+0

哦,好的。在保持缩进的同时,我很难粘贴。 – AlphaTested 2011-05-19 01:33:53

+0

@ user596100,如果你粘贴所有的代码,在HTML编辑器小部件中选中它并点击工具栏上的'{}'按钮,这也不算太坏。 (我知道,我通常忽略HTML编辑小工具中的工具栏,但是这个很有用。:) – sarnold 2011-05-19 01:37:22

回答

3

要连接新线串,使用+符号:

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

此外,要知道,你的while循环count每次递增是在Python不必要的。你可能只是这样做:

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

谢谢!那就是诀窍。 – AlphaTested 2011-05-19 01:36:21

+0

但是,这不是通过手动添加'\ n''来处理换行符的合适方法。 – Kabie 2011-05-19 01:40:57

+0

@Kabie是的,可能不会,他应该加入'os.linesep',但我不会挑剔 – 2011-05-19 01:50:07

1

一个简单的方法是:

print(string, file=theFileYouOpened)