假设我有一个包含以下信息的txt文件:
Name, Score
bob, 3
jack, 8
ben, 4
如何让python找到" bob",并将bob的整行复制到变量?
答案 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