【问题标题】:Python writelines skips first line of raw_inputPython writelines 跳过 raw_input 的第一行
【发布时间】:2015-10-12 00:29:02
【问题描述】:

我正在用 python 编写一个简单的日志程序。我使用了sys.stdin.readlines(),因此用户可以按回车键开始一个新段落,而不必退出程序。问题是当它将输入写入文本文件时,它会跳过他们输入的第一段。所以他们在开始新行之前写的任何东西都不会写入文件。

#!/usr/bin/python

import sys

def main(): #begin stand alone program

    print "\nPlease tell me about your day.\n";
    userEntry = raw_input() #assigns user's input
    todayEntry = userEntry
    todayEntry = sys.stdin.readlines()

    print "\nThank you! See you tomorrow!\n"

    with open('journal.txt', 'a') as f: 
        f.writelines(todayEntry) #write user's input to txt file


if __name__ == '__main__':
    main() #call to main() and complete program

【问题讨论】:

  • userEntry = raw_input() 读取一行,然后将其分配给todayEntry,然后丢弃此数据并用readlines() 结果覆盖它。基本上,raw_input() 是不需要的。
  • 基本上,删除 sys.stdin.realines() 行。它似乎没有多大用处。如果您想阅读多个段落,您可能需要在 while 中使用 raw_input,并在特殊命令上使用 break

标签: python file input


【解决方案1】:

您正在使用userEntry = raw_input() 读取输入,因此userEntry 现在包含用户输入的第一行(因为这是raw_input() 所做的)。然后,您将使用todayEntry = sys.stdin.readlines() 阅读更多输入。 todayEntry 现在包含用户输入的任何其他内容(从 sys.stdin.readlines() 返回)。然后您将todayEntry 写入文件,因此该文件包含用户在第一行之后输入的内容。

【讨论】:

    【解决方案2】:

    你可以这样做:

    import sys
    
    todayEntry = ""
    print "Enter text (press ctrl+D at the last empty line or enter 'EOF'):"
    
    while True:
        line = sys.stdin.readline()
    
        if not line or line.strip()=="EOF":
            break
    
        todayEntry += line
    
    print "todayEntry:\n"
    print todayEntry
    

    样本输入:

    111
    
    222
    
    333
    ctrl+D
    

    输出:

    111
    
    222
    
    333
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-07
      • 2013-08-17
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      相关资源
      最近更新 更多