python从某些字符串值读取文件输出 [英] python read file output from certain string value

查看:193
本文介绍了python从某些字符串值读取文件输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从打印网卡的部分读取文本文件并从那里继续,但我不知道如何做到这一点。

I want to read the text file from the part where it prints Network Cards and continue from there, but i dont have a clue how to do this.

import os


def main():
    print "This is a file handling system"
    fileHandler()

def fileHandler():
    os.system('systeminfo>file.txt')
    foo = open('file.txt', 'r+')
    readFile = foo.read()
    x = readFile.startswith('Network Card')
    print x
    foo.close()

if __name__ == '__main__':
    main()


推荐答案

你没有需要先将子进程输出保存到文件中。您可以将其标准输出重定向到管道:

You don't need to save the subprocess output to a file first. You could redirect its stdout to a pipe:

from subprocess import check_output

after_network_card = check_output("systeminfo").partition("Network Card")[2]

after_network_card 包含第一个网卡之后的 systeminfo 的输出。

after_network_card contains output from systeminfo that comes after the first "Network Card"`.

如果您可以将输出作为文件对象访问,那么要使用网卡获取以该行开头的部分:

If you have access to the output as a file object then to get the part starting with the line with "Network Card":

from itertools import dropwhile

with open('file.txt') as file:
    lines = dropwhile(lambda line: "Network Card" not in line, file)

你也可以使用显式代表 -loop:

You could also use explicit for-loop:

for line in file:
    if "Network Card" in line:
       break
# use `file` here

文件是一个迭代器Python中的行。

A file is an iterator over lines in Python.

这篇关于python从某些字符串值读取文件输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆