[英]How to print line of a file after match an exact string pattern with python?
[英]Match exact string and print the line
我想在第 3 次出現delimiter
后檢查字符串是否與行中的子字符串匹配
mapping_name
= reversed
delimiter
= #
test_file.txt
內容
1#ABC#test#reversed_once#gm#999
2#WBC#test_1#reversed_first#gm#9998
3#TBC#tested#reversed_last#gm#9998
4#CBC#test#reversed_reversed#gm#999
5#ZBC#test#reversed#gm#9990
我做了如下
wf_string = []
batch_file = open("/home/tester/test_file.txt", 'r')
for lines in batch_file:
if mapping_name in lines:
print(lines)
wf_string.append(lines)
但它打印的是第4 and 5
行4 and 5
。 理想情況下,它應該只打印第5th
行
嘗試類似下面的操作(請注意,代碼假設您只想針對第四個字段進行匹配)
match = 'reversed'
with open('in.txt') as f:
for idx,line in enumerate(f,1):
if match == line.split('#')[3]:
print(f'match in line {idx}')
輸出
match in line 5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.