【问题标题】:getting output from a file using python使用python从文件中获取输出
【发布时间】:2017-07-05 14:08:53
【问题描述】:

我有一个包含数据的文件,我正在尝试从该文件中获取特定的输出。当我在循环中使用“return”[使用 return 进一步分离输出]语句时,它只打印输出的第一行。

我已经正确定义了所有变量:

def show_command(filename, startline, endline):
      with open(filename) as input_data:
            for line in input_data:
                  if line.strip() == startline:
                       break
            for line in input_data:
                  if line.strip() == endline:
                       break
                  output = line
                  return output
  show_command(filename, startline, endline)
#

它只打印总输出的第一行。

当前启动变量:

### 实际输出为

当前启动变量:

sup-1 NXOS 变量 = bootflash:/nxos.7.0.3.I4.6.bin 没有设置模块引导变量

下次重新加载时启动变量:

sup-1 NXOS 变量 = bootflash:/nxos.7.0.3.I4.6.bin 没有设置模块引导变量

#

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    好吧,您只返回捕获的行,您需要在返回之前收集所有行,例如:

    def show_command(filename, startline, endline):
        with open(filename, "r") as input_data:
            output = None  # hold our contents
            for line in input_data:
                if line.strip() == startline:
                    output = ""  # start collecting lines
                elif line.strip() == endline:  # end of our area of interest
                    break  # end the loop
                elif output is not None:  # if we started collecting lines...
                    output += line  # collect the current line
            return output  # return the collected lines
    

    或者如果你想用你的方法做到这一点:

    def show_command(filename, startline, endline):
        with open(filename, "r") as input_data:
            for line in input_data:
                if line.strip() == startline:
                    break
            output = ""
            for line in input_data:
                if line.strip() == endline:
                    break
                output += line
            return output
    

    【讨论】:

    • 非常感谢zwer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 2020-02-28
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    相关资源
    最近更新 更多