【发布时间】:2016-05-22 11:47:13
【问题描述】:
假设我有一个包含以下信息的 txt 文件:
Name, Score
bob, 3
jack, 8
ben, 4
如何让 python 找到“bob”,并将 bob 的整行复制到变量中?
【问题讨论】:
标签: python file python-3.x file-io
假设我有一个包含以下信息的 txt 文件:
Name, Score
bob, 3
jack, 8
ben, 4
如何让 python 找到“bob”,并将 bob 的整行复制到变量中?
【问题讨论】:
标签: python file python-3.x file-io
将表读入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
【讨论】:
您应该使用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'}
你应该把它包装在一个函数中。
【讨论】:
以下代码将以阅读模式打开文件,读取所有行,如果在任何行中找到bob,它将打印整行:
with open('path_to_your_text_file', 'r') as f:
lines = f.readlines()
for line in lines:
if "bob" in line:
print line
【讨论】: