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

时间:2016-05-22 11:47:13

标签: python file python-3.x file-io

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

Name, Score

bob, 3
jack, 8
ben, 4

如何让python找到" bob",并将bob的整行复制到变量?

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

您应该使用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'}

你应该将它包装在一个函数中。

答案 2 :(得分:-1)

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

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