Python Forum

Full Version: read a particular part from a file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello community.

I want to search in a text file for a Keyword to readout what is in the same line after the keyword.
Keyword and the contend i look for are seperated with a vertical dash "|"
Like this:

Source:

wordone|blaone
wordtwo|blatwo
wordthree|blathree
wordfour|blafour
...

Keyword is "wordfour"

read out result:
blafour

currently I have this code:

fo = open(filename, "rt")
#print ("Name of the file:\n", fo.name, '\n')

line = fo.readlines()
print ("Read Line: \n %s" %(line))
_____________________________________________________________
thanks for answering
You need to loop through the lines with a for loop, split them by '|', and check the first part with an if statement.
Just to show what @ichabod801 talk about.
When you do fo.readlines() it put contend in a list,which is not needed for this task.
The is the basic way to loop through the lines.
with open('lines.txt') as f:
    for line in f:
        print(line.strip())
Output:
wordone|blaone wordtwo|blatwo wordthree|blathree wordfour|blafour
This will solve it,i know it look like homework and we do not do that.
But %s the oldest Python string formatting is now irritating me,even it maybe should not Dodgy
I have use f-string in all i have done since 3.6 came out.
keyword = "wordfour"
with open('lines.txt') as f:
    for line in f:
        if keyword in line:
            print(f'Line with found keyword:\n{line.strip()}')
            print('-' * 10)
            print(f"Found keyword <{line.split('|')[1].strip()}>")
Output:
Line with found keyword: wordfour|blafour ---------- Found keyword <blafour>
Thank you. That helps a lot.
My next trial is to to extract my informations out of a line.

Like this:
+0125F|6t|INFO|jd|uiek|kd_xy

intendet result:
INFO

The "keyword" in this case is the "|" after INFO

rigt now i have this code:
keyword = '+025C|-1|NA|NA|'
with open('Q2P.txt') as f:
    for line in f:
        if keyword in line:
            #print(f'Line with found keyword:\n{line.strip()}')
            print('-' * 25)
            print(f"Stage \n{line.split('_')[1].strip('')}")
            break
I think the key to my problem is in ".strip('')" But i didn't find it yet.