在txt文件中搜索一个字符,并从其下面的一行返回一个字符(Searching a txt file for a character, and returning a character from a

编程入门 行业动态 更新时间:2024-10-28 13:26:27
在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: 5

Lets 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 line2

when 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)

更多推荐

本文发布于:2023-07-24 17:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1248870.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符   并从   文件   txt   Searching

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!