Home > database >  How to read long text file and print a part from text file
How to read long text file and print a part from text file

Time:01-31

I want to read a long text file after read, print a special id from the text file

enter image description here

read and get MY_ID from sample.txt file

code which try-

def read_long_text_file():

    with open("path\sample.txt", "r") as f:
        for line in f:
            for part in line.split():
                if "MY_ID=" in part:
                    print(part)
            print line

read_long_text_file()

basically from this code output is that

MY_ID=120562

my desire is that only id will print on terminal like as 120562

does anybody solve my solution?

CodePudding user response:

try this,

print(part.split("=")[1])

instead of:

print(part)

CodePudding user response:

You could use regex for that

import re

with open('file.txt', 'r') as f:
    for line in f:
        if match := re.search(r'(?<=MY_ID=)\d ', line):
            id = int(match.group(0))
            print(id) # 123456789

Assuming your text file looks like this:

# file.txt
abcdef
409283120983

MY_ID=123456789

9298301923
  • Related