Python:如何使程序在输入文件结束时终止
我正在做一项编程作业,说明中规定: 当程序到达输入文件的结尾或stdin上的文件结尾时(在Linux下从键盘键入control-D时),程序应终止 这就是我到目前为止所做的:Python:如何使程序在输入文件结束时终止,python,linux,input,while-loop,raw-input,Python,Linux,Input,While Loop,Raw Input,我正在做一项编程作业,说明中规定: 当程序到达输入文件的结尾或stdin上的文件结尾时(在Linux下从键盘键入control-D时),程序应终止 这就是我到目前为止所做的: userInput = rawInput() while userInput != "": #other stuff the program will do 这是我第一次用python编程,我正在使用pycharm编辑器。我有点困惑这是否有效。通常在java中,我会检查userInput是
userInput = rawInput()
while userInput != "":
#other stuff the program will do
这是我第一次用python编程,我正在使用pycharm编辑器。我有点困惑这是否有效。通常在java中,我会检查userInput是否为null,但python似乎没有null对象?此外,这是否解释了说明中“在Linux下从键盘键入control-D时”的部分
由于我在提交文件之前使用pyCharm编辑并运行文件,因此如何测试以模拟在Linux下从键盘键入control-D“要执行操作直到
EOF
,请参阅下面的示例代码。外部For
循环迭代到最后一行,或者您可以说,文件结束
infile = open('input.txt','r')
lines = infile.readlines()
whitespace_count=0
for data in lines:
#do your stuff here, for example here i'm counting whitespaces in input file
for character in data:
if character.isspace():
whitespace_count +=1
print whitespace_count
当您需要从STDIN直接执行您的工作时,请考虑下面的代码,这里“代码> sys .STDIN < /代码>就像读取输入文件一样。输入足够的输入后,点击CTRL+D直到程序出口
import sys
for line in sys.stdin:
for data in line:
for character in data:
if character.isspace():
whitespace_count +=1
print whitespace_count
当程序到达文件末尾时,首先终止程序
print (l,end='')
print l
print (l,end='')
print l
如果您正在使用Python 2.7
fp=打开(“sample.txt”、“r”)
对于fp中的l:
print (l,end='')
print l
现在,当在stdin中按下crtl+D时,我们可以使用异常处理来终止输入
尝试:
除:
print "User typed ctrl+d"
或者这就是rawInput()
?当函数到达文件末尾时,返回什么?