在python中的txt文件中搜索特定单词

在python中的txt文件中搜索特定单词,python,file,python-3.x,file-io,Python,File,Python 3.x,File Io,假设我有一个包含以下信息的txt文件: Name, Score bob, 3 jack, 8 ben, 4 如何让python找到“bob”,并将bob的整行复制到一个变量?以下代码将以读取模式打开一个文件,读取所有行,如果它在任何行中找到了bob,它将打印整行: with open('path_to_your_text_file', 'r') as f: lines = f.readlines() for line in lines: if "bob" in

假设我有一个包含以下信息的txt文件:

Name, Score

bob, 3
jack, 8
ben, 4

如何让python找到“bob”,并将bob的整行复制到一个变量?

以下代码将以读取模式打开一个文件,读取所有行,如果它在任何行中找到了
bob
,它将打印整行:

with open('path_to_your_text_file', 'r') as f:
    lines = f.readlines()
    for line in lines:
        if "bob" in line:
            print line

您应该使用
csv
模块,而不是自定义杂技

import csv
with open(csvfile) as f:
    reader = csv.DictReader(f)
    for row in reader:
        if row['Name'] == 'bob':
            got = row
            break
>>> got
>>> {' Score': ' 3', 'Name': 'bob'}

您应该将其包装在函数中。

将表读入数据框并使用
执行查询通常很方便。例如:

import pandas as pd

# The text file
txt_file = r'C:\path\to\your\txtfile.txt'

# Read the .txt file into a pandas dataframe
df = pd.read_table(txt_file, sep = ",")

# Isolate the row based on your query
row = df.loc[df['Name'] == 'ben']

>>> row
  Name   Score
2  ben       4