Python如何在不删除现有内容的情况下继续写入文件

编程入门 行业动态 更新时间:2024-10-27 22:27:13
本文介绍了Python如何在不删除现有内容的情况下继续写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在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如何在不删除现有内容的情况下继续写入文件

本文发布于:2023-05-31 12:02:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/391388.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:情况下   文件   内容   如何在   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!