Python Forum

Full Version: Need help to retrieve a particular string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I need your help to retrieve/display particular string in a file.

file1:
=====
567812345676-123
p-45yt7u75402

I want to get the record starts with p- record in a file.

Appreciate your help on this.

Thx in advance
What have you tried?
Hi,

I tried using the below but always it should be the last record in a file.

with open(r'C:\Users\lokesh\file.txt') as f:
print(f.readlines()[-1].split())

and even the output is showing like as below

output:
=====
['p-45yt7u75402']

however i don't want to get [(paranthesis)and '(single quotes). Please let me know how to achieve the record starting with p-

Thx in advance
Maybe you can iterate over all lines of file and check whether line starts with 'p-', something along those lines:

with open(r'C:\Users\lokesh\file.txt') as f:
    for line in f:
        if line.startswith('p-'):
            # do_something