简体   繁体   中英

Finding numbers in a .txt file of thousands of numbers ending in a specific set of 4 numbers

What I currently have written I can find specific numbers starting with but I need numbers ending with.

The data file looks like this:

1231231234
1231231234
1231231234
etc...

My code:

import re
with open("test.txt") as f:
   with open("testoutput.txt", "w") as f1:
       for line in f:
           if re.match("^123", line):
               f1.write(line)

Its not clear why you're using ^123 to match your number.

In regex paradigm, "ending with something" translates to "something + end of line". Which is something$ in most regex dialects. Take a look into official python doc on this.

Not regarding actual question, hint: you can write multiple context managers in one line, like

with open("test.txt") as f, open("testoutput.txt", "w") as f1:
    ...

No regex needed, you could very well use endswith :

string = """
1231231234

1231231234

1231231234
888
"""

numbers = [line 
    for line in string.split("\n") 
    if line and not line.endswith('1234')]
print(numbers)

Which yields

['888']


Or, the other way round:

 string = """ 1231231234 1231231234 1231231234 888 """ numbers = [line for line in string.split("\\n") if line and line.endswith('1234')] print(numbers) # ['1231231234', '1231231234', '1231231234'] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM