简体   繁体   English

我如何 go 关于将文本保存在文本框中?

[英]How do I go about saving text in a text-box?

How would I go about saving multiple lines of text without stretching out my code?我将如何在不延长代码的情况下保存多行文本?

It's hard to put in to words but I'll give an example of what I've done.很难用言语表达,但我会举一个我所做的例子。

wri_name=input("What do you want to call your new file? (Extension included): ")
print("Type what you want your file to contain!: ")
wri_con1=input("1> ")
with open((wri_name), 'w') as f:
   f.writelines(["\n" + wri_con1])

I'm trying to make an improvement by making a text-box that is seemingly endless but can still be saved into a file.我试图通过制作一个看似无穷无尽但仍可以保存到文件中的文本框来进行改进。 Take Microsoft Notepad as an example.以微软记事本为例。 I'm trying to replicate a program similar to that but I've really been scratching my head about what I could do here.我正在尝试复制一个类似的程序,但我真的一直在摸索我能在这里做什么。

When you write in loop then you have to open in append mode - open(..., "a") - because write mode removes previous content.当您在循环中写入时,您必须在append mode打开 - open(..., "a") - 因为write mode会删除以前的内容。

filename = input("What do you want to call your new file? (Extension included): ")
print("Type what you want your file to contain!: ")

while True:
    text = input("1> ")
    
    if text.lower() == "quit":
        break
    
    with open(filename, 'a') as f:
       f.write(text + "\n")

Or you have to open it only once或者你只需要打开一次

filename = input("What do you want to call your new file? (Extension included): ")
print("Type what you want your file to contain!: ")

# --- before loop ---

f = open(filename, 'w')

# --- loop ---

while True:
    text = input("1> ")
    
    if text.lower() == "quit":
        break
    
    f.write(text + "\n")

# --- after loop ---

f.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 python 中为基于文本的冒险游戏创建保存系统? - How can I go about creating a saving system for a text based adventure game in python? 我如何在Pygame中制作可点击的文字? - How would I go about making clickable text in Pygame? Python Tkinter通过函数更新文本框内容 - Python Tkinter updating text-box content via a function HTML文本框在空格后不读取数据 - HTML text-box does't read data after spaces 我有这个包含一堆字节和一些文本的非文本文件,我如何 go 将文本与 rest 干净地分开? - I have this non-text file that has a bunch of bytes and some text, how do I go about separating the text cleanly from the rest? 如何在Tkinter中更新此文本框的文本? - How do I update this Text Box's text in Tkinter? 在 tkinter 如何将文本框中的文本作为变量访问 - in tkinter how do I access text in a text box as a variable 如何在控制台中打印文本框中的文本? - How Do I have the text in the text box get printed in the console? Pygame:我将如何设置文本对象,但文本是否会不断变化? - Pygame: How would I go about setting a text object, BUT the text is meant to keep changing? 如何制作交互式 tkinter 文本框,然后是输入框,然后是文本框作为对输入的响应 - How do I make an interactive tkinter text box, then entry box, then text box as a response to the entry
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM