Python writelines skips first line of raw_input

我们两清 提交于 2021-01-28 22:04:56

问题


I am writing a simple journal program with python. I used sys.stdin.readlines() so the user could press enter to start a new paragraph and not have to program quit. The problem is that when it writes the input to the text file it skips the first paragraph they enter. so anythying that they write before starting a new line isn't written to the file.

#!/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

回答1:


You're reading input with userEntry = raw_input(), so userEntry now contains the first line the user enters (because that's what raw_input() does). You're then reading more input with todayEntry = sys.stdin.readlines(). todayEntry now contains whatever else the user enters (returned from sys.stdin.readlines()). You're then writing todayEntry to a file, so the file contains what the user entered after the first line.




回答2:


You can do something like this:

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

sample input:

111

222

333
ctrl+D

Output:

111

222

333


来源:https://stackoverflow.com/questions/33071599/python-writelines-skips-first-line-of-raw-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!