[英]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"`. after_network_card
包含systeminfo
输出,该输出位于第一个“网卡”之后。
If you have access to the output as a file object then to get the part starting with the line with "Network Card"
: 如果您可以将输出作为文件对象进行访问,则可以从"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
-loop使用显式:
for line in file:
if "Network Card" in line:
break
# use `file` here
A file is an iterator over lines in Python. 文件是Python中各行的迭代器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.