好的我有这个文本文件结构
Customer ID: 1
Customer Name: John
Customer Sale: 5
假设我希望使用客户ID搜索此条目的文本文件并返回客户销售的内容:这是5
我有类似的东西
with open("sales.txt", "r") as salesFile:
lines = salesFile.readlines()
for line in lines:
if (str(ID)) in line:
return ????
不确定如何从我搜索
的两行中返回一个值提前致谢
答案 0 :(得分:0)
不需要分割线,那么file将是一个迭代器: 你可以这样做:
def match_line(ID, f):
with open(f) as file:
for line in file:
if str(ID) in line:
for line2 in file:
if 'Sale' in line2:
return line2
用文件调用时:
In [9]: match_line(1, 'sales.txt')
Out[9]: 'Customer Sale: 5\n'
这假设您想要带有字符串' Sale'在它上面,如果你想要之后的2行:
def match_line(ID, f):
with open(f) as file:
for line in file:
if str(ID) in line:
next(file)
return next(file)
答案 1 :(得分:0)
你想要接下来的两行,这就是匹配后的下两行
with open("a.txt") as sales:
lines=sales.readlines()
for i in range(len(lines)-1):
if ("ID: "+str(5)) in lines[i]:
print lines[i+1],lines[i+2]
<强> 输出: 强>
Customer Name: John
Customer Sale: 5
使用枚举器:
with open("a.txt") as sales:
lines=sales.readlines()
for i,a in enumerate(lines):
if ("ID: "+str(5)) in a:
print lines[i+2]
<强>输出:强>
Customer Sale: 5
答案 2 :(得分:0)
在这里你可以找到两个解决方案,第二个是pythonic。这两个函数都将Customer ID
作为参数,第二个是客户ID行与要返回的所需行之间的偏移量,最后一个是输入文件。如果id不存在,则函数返回None
。
如果您不需要将偏移量传递给函数,则可以删除它并在函数内部声明
def get_id_details(c_id,offset,in_file):
base_line = 'Customer ID: %s' % c_id
find = False
with open(in_file) as f:
for line in f:
if (base_line == line.rstrip('\r\n') and not find ):
find = True
if (find):
offset -=1
if offset ==-1:
return line
return None
def get_id_details_2(c_id,offset,in_file):
base_line = 'Customer ID: %s' % c_id
with open(in_file) as f:
for line in f:
if (base_line == line.rstrip('\r\n')):
try:
for _ in range(offset-1):
f.next()
return f.next()
except StopIteration:
return None
print get_id_details(2,2,'in.txt')
// result is Customer Sale: 5
print get_id_details(8,6,'in.txt')
// result is None
print get_id_details_2(2,2,'in.txt')
// result is Customer Sale: 6
print get_id_details_2(5,2,'in.txt')
// result is None
输入文件
Customer ID: 1
Customer Name: John1
Customer Sale: 5
Customer ID: 2
Customer Name: John2
Customer Sale: 6
Customer ID: 4
Customer Name: John3
Customer Sale: 7
Customer ID: 3