Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

Getting index based on the first characters from a file in python using Regex

I'm trying the get the index of a string in a file based on a regex which is looking for the value '01', but without success, can someone help me?

My Code

#!/bin/python

import os
import re

finalListFileTxt = 'C:\USER_ATU\Processing of TTSCOF00.IMG for file status\MSS_Sample\listOfFilesFromTtsFile.txt'
searchedIndexValue = []
with open(finalListFileTxt,"r") as arq:
    for linha in arq.readlines():
        pattern = r'^01$'
        searchedIndexValue = re.findall(pattern,linha)
        print(searchedIndexValue)

Actual Output

[]
[]
[]
[]
[]
[]

Input

That's a sample of the content of the file I'm using :

022413102101212003
022418102101212003
022423102101212003
022428102101212003
022433102101212003
022438102101212003
022443102101212003
012448102101212003
012453102101212003
021437032812202003
021442032812202003

What I'm looking for

My idea was to see in my list(searchedIndexValue) the row(not the content of the row) of each row starting with 01 in my file., the values : 8,9

question from:https://stackoverflow.com/questions/65903235/getting-index-based-on-the-first-characters-from-a-file-in-python-using-regex

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@jasonharper is right. In addition to what he said, if you want to get the row numbers, you should make something like this:

import os
import re

finalListFileTxt = 'teste.txt'
searchedIndexValue = []
with open(finalListFileTxt,"r") as arq:
    for i,linha in enumerate(arq.readlines()):
        pattern = r'^01'
        if re.findall(pattern,linha):
            searchedIndexValue.append(i)
print(searchedIndexValue)

enumerate will iterate arq.readlines() and return a pair of linenumber and line.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...