【问题标题】:Python: How to make program terminate when the end of the input file is reqched [duplicate]Python:到达输入文件末尾时如何使程序终止[重复]
【发布时间】:2018-06-23 03:02:51
【问题描述】:

我正在做一个编程任务,方向说明:

“当你的程序到达输入文件的结尾,或者标准输入的文件结尾(当在 Linux 下从键盘输入 control-D 时)时,你的程序应该终止。”

这是我目前所拥有的:

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

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

由于我在上交文件之前使用 pyCharm 编辑和运行文件,如何测试以模拟在 Linux 下从键盘键入 control-D 的情况?

【问题讨论】:

标签: python linux input while-loop raw-input


【解决方案1】:

要执行直到 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  

【讨论】:

    【解决方案2】:

    当程序到达文件末尾时首先终止程序。

    1. 使用 open() 打开文件

      fp=open("sample.txt","r")

    2. 使用 for 循环读取行

      fp 中的 l:

    3. 打印线条

    fp=open("sample.txt","r")

    fp 中的 l:

    print (l,end='')
    

    如果您使用的是 python2.7

    fp=open("sample.txt","r")

    fp 中的 l:

    print l
    

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

    尝试:

    str1=raw_input("Enter the String :")
    
    print "Given String :",str1
    

    除了:

    print "User typed ctrl+d"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-25
      • 2019-12-31
      • 1970-01-01
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多