简体   繁体   中英

How would I search a text file for a specific name, and print the whole line with Python?

My code is currently:

def GrabCPUInfo():
    with open("cpu_list.txt", "r") as file:
        line = file.readlines()
        if cpu in line:
            print(line)
        else:
            print("Incorrect information")

My issue is that it just keeps printing out "Incorrect information" instead of printing out the whole line that includes the cpu name.

Let's say I have a file cpu_list.txt with the value

CPU 1: Example
CPU 2: Example
CPU 3: Example

You could do something like

with open('cpu_list.txt','r') as f:
    # Read content as well removing \n
    content = [line.strip() for line in f.readlines()]

    # print(content)
    # ['CPU 1: Example', 'CPU 2: Example', 'CPU 3: Example']
    for line in content:
        if 'CPU 1' in line:
            print(line)
        else:
            print('Invalid Info')
        break

The output

CPU 1: Example

readlines() returns a list of strings where each element of the list is an entire line in the text file. For example, using readlines on this text file...

bob
joe
emily

would create the list ['bob\\n', 'joe\\n', 'emily\\n']

Unless cpu matches an entire line exactly (including the newline character), using in like this won't work. You can still use in on the individual strings to test if the string contains cpu . Try something like this:

def GrabCPUInfo():
    with open("test.txt", "r") as file:
        lines = file.readlines()
        for line in lines:
            if cpu in line:

I removed the else block because it would just print "Incorrect information" over and over again for every line that didn't have the correct string.

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