0

This is the sample file, I would like to check if "field5" exists in file, if exists check if 67890 exits, if exists then print corresponding values for "field5"

sample output:

112

START
field1
field2
field3
field4
field5
field6
END

12345|5|1|2|3|4|111|555
67890|5|6|7|8|9|112|000
1
  • You seem to be missing some python code in your question. If you have some, even if wrong, please edit the question to include it Commented Jul 30, 2017 at 23:16

1 Answer 1

1

Finding content in file you can achieve by looping over its lines like so:

def process_text():
    f = open('filename.txt')
    for line in f:
        if 'field5' in line:
            break
    else: return
    f.seek(0) # get back to the begining of the file (if you want to)
    for line in f:
        if '67890' in line:
            numbers = line.split(sep='|') # getting the list that contains the numbers
    else: return

    print(numbers[-1]) # print the last element

NOTE: This is python3.5.2. In python 2.7 split method should look like this: line.split('|') (without keywords).

Sign up to request clarification or add additional context in comments.

4 Comments

Hi, I forgot to mention, if this a position based on above? if we have field6.
Position of what, 67890 or the numbers after?
Hi, Lets say field5 exists, then 112 is the value corresponding to field5 when you line starting with 67890 in the first column. 67890|5|6|7|8|9|112|000
Then you have to change the last line to print(numbers[1+5]), because print(numbers[-1]) means that you're gonna print the last number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.