【问题标题】:Python: input saving multiline stringPython:输入保存多行字符串
【发布时间】:2023-04-08 18:00:01
【问题描述】:
while True:
try:
    line = input("paste:")
except EOFError:
    break

f = open("notam_new.txt", "w+")
f.write(line)
f.close()

此代码仅返回 Ctrl+D 后多行的最后一行

我也试过了:

notam = input("paste new notam: ")

f = open("notam_new.txt", "w+")
f.write(notam)
f.close()

只获取第一行。

有什么想法吗?

【问题讨论】:

    标签: python-3.x multiline


    【解决方案1】:

    您将line 设置在一个循环中,因此每次迭代您只是用下一个迭代覆盖所述行您需要将您的行累积在一个列表中(在while True 之前创建),以便您可以跟踪所有这些,然后循环写入文件。另外,您还需要添加一个换行符,因为input() 会删除它。

    lines = []
    while True:
        try:
            lines.append(input("paste:"))
        except EOFError:
            break
    
    with open("notam_new.txt", "w+") as f:
        for line in lines:
            f.write(line)
            f.write('\n')
    

    【讨论】:

    • 谢谢。但是我怎样才能删除它:粘贴几行后paste:paste:paste:paste:paste:?除了 Ctrl+D 之外还有其他选择吗?
    • “但是我怎样才能删除它:粘贴:粘贴:粘贴:粘贴:粘贴:粘贴几行后?”不知道,不提供提示吗?或者不要使用input 并直接从sys.stdin 读取(它更复杂但也更灵活)。 “除了 Ctrl+D 之外,还有其他选项可以结束它吗?”这取决于你,你可以在 C-c 上打破它,或者当你得到一个空行或连续两个空行时。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-19
    相关资源
    最近更新 更多