在Windows中编写我的python 3.3程序,我遇到了一个小问题.我正在尝试将一些指令行写入文件以使程序执行.但是每次我file.write()下一行时,它都会替换上一行.我希望能够继续向该文件写入尽可能多的行.注意:使用"\ n"似乎不起作用,因为您不知道会有多少行.请帮忙!这是我的代码(作为循环,我多次运行此代码):
Writing my python 3.3 program in Windows, I've run into a little problem. I'm trying to write some lines of instructions to a file for the program to execute. But every time I file.write() the next line, it replaces the previous line. I want to be able to keep writing as many lines to this file as possible. NOTE: Using "\n" doesn't seem to work because you don't know how many lines there are going to be. Please help! Here is my code (being a loop, I do run this multiple times):
menu = 0 while menu != None: menu = lipgui.choicebox("Select an option:", choices=["choice1", "choice2", "choice3"]) file = open("file.txt", "w") if menu == "choice1": text_to_write = lipgui.enterbox("Text to write:") file.write(text_to_write)推荐答案
每次打开要写入的文件都会被删除(被截断).而是打开文件进行附加,或打开文件一次并保持打开状态.
Every time you open a file for writing it is erased (truncated). Open the file for appending instead, or open the file just once and keep it open.
要打开文件进行追加,请使用a代替w作为模式:
To open a file for appending, use a instead of w for the mode:
while menu != None: menu = lipgui.choicebox("Select an option:", choices=["choice1", "choice2", "choice3"]) file = open("file.txt", "a") if menu == "choice1": text_to_write = lipgui.enterbox("Text to write:") file.write(text_to_write)或在循环外打开文件 :
file = open("file.txt", "w") while menu != None: menu = lipgui.choicebox("Select an option:", choices=["choice1", "choice2", "choice3"]) if menu == "choice1": text_to_write = lipgui.enterbox("Text to write:") file.write(text_to_write)或者在您第一次需要时仅一次:
or just once the first time you need it:
file = None while menu != None: menu = lipgui.choicebox("Select an option:", choices=["choice1", "choice2", "choice3"]) if file is None: file = open("file.txt", "w") if menu == "choice1": text_to_write = lipgui.enterbox("Text to write:") file.write(text_to_write)更多推荐
Python如何在不删除现有内容的情况下继续写入文件
发布评论