How to search for word in text file and print part of line with Python?

后端 未结 2 1165
南旧
南旧 2021-01-14 15:21

I\'m writing a Python script. I need to search a text file for a word and then print part of that line. My problem is that the word will not be an exact match in the text fi

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-14 15:51

    Here's one way - split each line by spaces, then search each part for "color=":

    with open("textfile.txt") as openfile:
        for line in openfile:
            for part in line.split():
                if "color=" in part:
                    print part
    

提交回复
热议问题