Python文本文件输入错误

2024-05-19 00:03:25 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我正在编写一个程序,当我输入一个文本时,它会将其写入一个文本文件。我遇到的第一个问题是,每次我输入内容时,它都会覆盖自身。我想要的是,每次我输入内容时,它都会创建一个新行

textinput= "\TextInput: "
inputtext = input(textinput)

with open("Text Input.txt", "w") as f:
    for text in inputtext:
        f.write(text)

我通过在for循环中添加f.write("\n")修复了这个问题。问题是,在for循环中,它会对每个字母不断重复自己。把它放在for循环之外是行不通的,它会像过去一样不断地重写自己。有什么解决办法吗


Tags: text文本程序内容forinputwithtextinput
1条回答
网友
1楼 · 发布于 2024-05-19 00:03:25

您不需要将每个字符写入文件。你可以一次写一整行

请使用附加标志"a"而不是写入标志"w"来解决问题

这将解决您的问题:

textinput= "\TextInput: "
inputtext = input(textinput)
inputtext += "\n"

with open("Text Input.txt", "a") as f:
    f.write(inputtext)
网友
2楼 · 发布于 2024-05-19 00:03:25

当然,它会覆盖,所以您必须使用appenda,而不是使用writew作为参数

 textinput= "\TextInput: "
           inputtext = input(textinput)

 with open("Text Input.txt", "a") as f:
    for text in inputtext:
         f.write(text)
网友
3楼 · 发布于 2024-05-19 00:03:25

我认为最简单的应该是

with open("test_input.txt", "a") as ff:
    print(input("Text Input: "),file=ff)

如果只使用print(,file=),则不需要为\n等设置ned

相关问题 更多 >

    热门问题