Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python. extracting string from file [duplicate]

Tags:

python

regex

I have a file similar to this:

RANDOMTEXTSAMPLE*
$SAMPLERANDOMTEXT
RANDOMSAMPLE*TEXT

I'm trying to extract and put into a list all instances of "sample" that have * at the end.

I tried with something like this:

import re

with open('file1.txt') as myfile:
content = myfile.read()

text = re.search(r'[0-9A-Z]{7}\*', content)
with open("file2.txt", "w") as myfile2:
myfile2.write(text)

However I would only get me the first result it found.

Any recommendations on how can I get all the instances of sample that end with * in a list, without adding the * to the list will be appreciated.

Thanks

EDIT: small corrections

like image 733
motionsickness Avatar asked Nov 24 '25 07:11

motionsickness


1 Answers

You can try this:

import re

samples = []

with open('file1.txt') as myfile:
    for line in myfile.readlines():
        if re.search(r'[0-9A-Z]{6}\*', line):                
            samples.append(line)

# print('SAMPLES: ', samples)

with open("file2.txt", "w") as myfile2:
    for s in samples:
        myfile2.write(s)

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!