我的长期目标是能够读取文件,并查找包含特定ID的多行并从这些行中提取数据。现在,我正在尝试查找包含这些ID的某些行并打印这些行,以使我知道自己拥有正确的数据。
每行以{“ id”:“ 101”开头,并且具有不同的ID号,但是它也具有较长的记录号,并且在任何记录号中都可能包含一些ID号,因此我正在搜索“” id#“”像下面一样。
handle = open('info.txt')
for line in handle:
if not '"101"' in line:
continue
print(line)
上面的代码可以工作,但是如果我想提取多个值,例如101110170230,我想尝试这样的事情。
handle = open('info.txt')
for line in handle:
if not '"101"' '"110"' '"170"' '"130"' in line:
continue
print(line)
但这似乎不起作用。我也尝试创建一个列表,但似乎可以使用列表。
如果要查找任何ID,请使用any
。
ids = ['101', '110', '120', '170', '130']
with open('info.txt') as handle:
for line in handle:
if not any(id_ in line for id_ in ids):
continue
print(line)
我使用了该with
语句,因为它会在with
块之后关闭文件-您忘记了。我命名为变量id_
,并不是id
因为我不想覆盖内置变量id
。
因为您说过“每行以开头{"id": "101"
,并且具有不同的ID号”,所以您可能不仅要检查id是否在行中,还需要检查行是否以此顺序开头。
with open('info.txt') as handle:
for line in handle:
if not any(line.startswith(f'{{"id": "{id_}"') for id_ in ids):
continue
print(line)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句