在txt文件中搜索一个字符,并从其下面的一行返回一个字符(Searching a txt file for a character, and returning a character from a line below it)
好的我有这个文本文件结构
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 ????不确定如何从我正在搜索的内容中返回两行值
提前致谢
Ok I have this text file structure
Customer ID: 1 Customer Name: John Customer Sale: 5Lets say I wish to search the text file for this entry using the customer id and return the contents of customer sale: which is 5
I have something similar to this
with open("sales.txt", "r") as salesFile: lines = salesFile.readlines() for line in lines: if (str(ID)) in line: return ????Not sure how to return a value two lines down from what I'm searching for
Thanks in advance
最满意答案
不需要分割线,然后文件将是一个迭代器:你可以做类似的事情:
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)No need for splitlines, then file will be a iterator: You can do something like:
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 line2when called with file:
In [9]: match_line(1, 'sales.txt') Out[9]: 'Customer Sale: 5\n'This is assuming you want the line with the string 'Sale' on it, if you want 2 lines after then:
def match_line(ID, f): with open(f) as file: for line in file: if str(ID) in line: next(file) return next(file)更多推荐
发布评论