Python:如何在请求输入文件结尾时终止程序

2024-06-26 00:28:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一项编程作业,指导说明如下:

当程序到达输入文件的结尾或stdin上的文件结尾时(在Linux下从键盘键入control-D时),程序应该终止

到目前为止,我得到的是:

    userInput = rawInput()
    while userInput != "":
        #other stuff the program will do

这是我第一次用python编程,我使用的是pycharm编辑器。我有点困惑这是否有效。通常在java中,我会检查userInput是否为null,但python似乎没有null对象?另外,这是否说明了指令中“当在Linux下从键盘键入control-D”的部分吗?在

既然我使用pyCharm来编辑和运行我的文件,那么在Linux下,当从键盘输入control-D时,如何进行测试来模拟?在


Tags: 文件程序键入linux编程结尾stdin作业
2条回答

要执行到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直到程序退出

^{pr2}$

当程序到达文件结尾时首先终止它。在

  1. 使用open()打开文件

    fp=打开(“样本.txt“,”r“)

  2. 使用for循环读取行

    对于fp中的l:

  3. 打印线条

fp=打开(“示例.txt“,”r“)

对于fp中的l:

print (l,end='')

如果你正在使用python2.7

fp=打开(“示例.txt“,”r“)

对于fp中的l:

^{pr2}$

现在我们可以在按下crtl+D时使用异常处理来终止输入标准。这里我正在指定示例程序

尝试:

str1=raw_input("Enter the String :")

print "Given String :",str1

除了:

print "User typed ctrl+d"

相关问题 更多 >