Python编写行跳过raw_input的第一行 [英] Python writelines skips first line of raw_input
问题描述
我正在用python编写一个简单的日记程序.我使用了 sys.stdin.readlines()
,因此用户可以按Enter键开始一个新段落,而不必退出程序.问题在于,当将输入内容写入文本文件时,它会跳过它们输入的第一段.因此,他们在开始新行之前编写的所有内容都不会写入文件中.
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
推荐答案
您正在使用 userEntry = raw_input()
读取输入,因此 userEntry
现在包含第一行用户输入(因为这就是 raw_input()
所做的事情).然后,您将使用 todayEntry = sys.stdin.readlines()
阅读更多输入.现在, todayEntry
包含用户输入的其他内容(从 sys.stdin.readlines()
返回).然后,您将 todayEntry
写入文件,因此该文件包含用户在第一行之后输入的内容.
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.
这篇关于Python编写行跳过raw_input的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!