I am trying to create a script that search for strings of numbers with only specific length numbers from an output.txt.
Example output.txt:
12345678
77777
12123887
When I use:
import re
f = open('output.txt', 'r')
strings = re.findall(r'(\d{5,5})', f.read())
print strings
I would like to get only output: 77777
instead of:
12345
77777
12123
Use ^(\d{5})$
and re.MULTILINE
>>> import re
>>> data = '''12345678
77777
12123887'''
>>> p = re.compile(r'^(\d{5})$', re.MULTILINE)
>>> re.findall(p, data)
['77777']
>>>
A non-regex solution. This can be done by just getting the length of each name and getting the one of interest by also validating isdigit
:
with open('output.txt') as f:
file_names = [name.strip() for name in f.readlines() if name.strip().isdigit() and len(name.strip()) == 5]
print(file_names)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With