问题
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