python read file output from certain string value

醉酒当歌 提交于 2019-12-11 10:58:31

问题


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()

回答1:


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 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)

You could also use explicit for-loop:

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

A file is an iterator over lines in Python.



来源:https://stackoverflow.com/questions/22529862/python-read-file-output-from-certain-string-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!