![](/img/trans.png)
[英]How to search for word in text file and print part of line with Python?
[英]How would I search a text file for a specific name, and print the whole line with Python?
我的代碼目前是:
def GrabCPUInfo():
with open("cpu_list.txt", "r") as file:
line = file.readlines()
if cpu in line:
print(line)
else:
print("Incorrect information")
我的問題是它只是不斷打印出“不正確的信息”,而不是打印出包含 cpu 名稱的整行。
假設我有一個帶有值的文件cpu_list.txt
CPU 1: Example
CPU 2: Example
CPU 3: Example
你可以做類似的事情
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
輸出
CPU 1: Example
readlines()
返回一個字符串列表,其中列表的每個元素都是文本文件中的整行。 例如,在此文本文件上使用readlines
...
bob
joe
emily
將創建列表['bob\\n', 'joe\\n', 'emily\\n']
除非cpu
完全匹配整行(包括換行符),否則像這樣使用in
是行不通的。 您仍然可以in
單個字符串上使用in
來測試字符串是否包含cpu
。 嘗試這樣的事情:
def GrabCPUInfo():
with open("test.txt", "r") as file:
lines = file.readlines()
for line in lines:
if cpu in line:
我刪除了else
塊,因為它只會為沒有正確字符串的每一行一遍又一遍地打印“不正確的信息”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.