Mystery
Mystery

Reputation: 81

Read only specific part first two lines from text file in python

Here's my problem description:- i have a .txt file to be read and i want only specific part of the first two lines to be read and printed

here's the txt

NAME: "AAAAAA AAAAAA", DESCR: "bbbbbb bbbbbb, ccc. ccccccccccccccccccccccccccccccc "
PID: dd-ddddd-d        , VID: 23s  , SN: qqqqqqqqq              #Here

NAME: "ggggggggggg", DESCR: "hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh" 
PID: yy-yyyyy-yy-yy    , VID: Q23  , SN: ftyujnbghjn

The above text is as it is written in the text file ans i wan to read only PID: dd-ddddd-d and SN: qqqqqqqq from the second line (see #Here in txt) and ignore the rest.!

thx for the help.! :-)

Upvotes: 0

Views: 1172

Answers (3)

gregory
gregory

Reputation: 12993

with open('file', 'r') as f:
    file_as_list = f.readlines()
for line in file_as_list:
    result = re.findall(r'PID:\s[a-z-]+|SN:\s[a-z-]+', line)
    if result:
        print(result)

output:

['PID: dd-ddddd-d', 'SN: qqqqqqqqq']
['PID: yy-yyyyy-yy-yy', 'SN: ftyujnbghjn']

Upvotes: 0

DPS
DPS

Reputation: 1003

You can use readlines(), it converts text file into lists.

Eg:

with open('demo.txt') as file:
    print(file.readlines()[1])   //fetches second line as I have used indexing here([1])

Expected output will be PID: dd-ddddd-d , VID: 23s , SN: qqqqqqqqq

I have used with open() because it automatically closes the file once it has been read.

To get the result:

with open('demo.txt') as file:
    second_line = file.readlines()[1]
    list_again = second_line.split(',')

Expected output: ['PID: dd-ddddd-d ', ' VID: 23s ', ' SN: qqqqqqqqq \n']

Now you can use indexing to retrieve specific values.

Upvotes: 1

SM Abu Taher Asif
SM Abu Taher Asif

Reputation: 2331

you can read line by line and find the necessary data:

with open('yourTextFile.txt', "r") as f:
    for line in f:
        if "PID" in line or "SN" in line:
            dataArr = line.split(",")
            for data in dataArr:
                if 'PID' in data:
                    print(data)
                if 'SN' in data:
                    print(data)

output:

PID: dd-ddddd-d        
 SN: qqqqqqqqq              

PID: yy-yyyyy-yy-yy    
 SN: ftyujnbghjn            

Upvotes: 2

Related Questions