[英]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.我的问题是它只是不断打印出“不正确的信息”,而不是打印出包含 cpu 名称的整行。
Let's say I have a file cpu_list.txt
with the value假设我有一个带有值的文件
cpu_list.txt
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. readlines()
返回一个字符串列表,其中列表的每个元素都是文本文件中的整行。 For example, using readlines
on this text file...例如,在此文本文件上使用
readlines
...
bob
joe
emily
would create the list ['bob\\n', 'joe\\n', 'emily\\n']
将创建列表
['bob\\n', 'joe\\n', 'emily\\n']
Unless cpu
matches an entire line exactly (including the newline character), using in
like this won't work.除非
cpu
完全匹配整行(包括换行符),否则像这样使用in
是行不通的。 You can still use in
on the individual strings to test if the string contains cpu
.您仍然可以
in
单个字符串上使用in
来测试字符串是否包含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.我删除了
else
块,因为它只会为没有正确字符串的每一行一遍又一遍地打印“不正确的信息”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.