简体   繁体   中英

python read file output from certain string value

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM