添加更多行

时间:2013-05-06 12:54:53

标签: python python-2.7

我正在尝试使用Python制作一个小型文本创建器应用程序。该概念与普通文本创建者(例如记事本)相同。但是我很难让用户输入很多段落。到目前为止,我只能允许用户键入2个段落。有没有人可以帮助我?这是我的剧本:

print "Welcome to 'Python Flat Text Creator'."
print "Please enter the name of your file and its extension (.doc atau .txt)."

filename = raw_input("> ")
target = open(filename, 'w')
typeyourtext = raw_input("Type below: \n")
target.write(typeyourtext + "\n")
typeyourtext = raw_input("\n")
target.write(typeyourtext + "\n")
target.close()

2 个答案:

答案 0 :(得分:1)

一个简单的答案就是简单地将文本的输入和显示放在while(true)块中并等待某事(按键或字符集)来打破循环。但我不确定你是否愿意这么做。

尝试将其中的字符作为其他文本编辑器逐个插入 - 例如,查看Vim。在那里使用的系统相当简单方便。

修改

获取按键:How to accept keypress in command line python?

同时进行真正的周期:http://wiki.python.org/moin/WhileLoop

在每个循环结束时,如果输入字符不是chr(27),这是ESC键,则附加到您正在创建的文本并显示它..但这不适用于体积很大..

答案 1 :(得分:0)

当用户根本不输入任何内容时,您可以使用while循环设置结束。

target = open(filename, 'w')
previousKeypress = 0

print("Type below:\n")

while previousKeypress != "":
    typeyourtext = raw_input("")
    target.write(typeyourtext + "\n")
    previousKeypress = typeyourtext

target.close()

如果您打算让用户通过无输入在文档中添加其他新行,您可以设置条件以对某些字符组合做出反应,例如“abc123”可能会结束它。

您甚至可以要求用户在程序的最开始通过另一个raw_input设置此结束组合。