RevCity
RevCity

Reputation: 13

regex output to a text file

I'm trying to write a python Script that write regex output (IP Addresses) to a text file. The script will rewrite the file each time it runs. Is there any better way to do it?

import re

pattern = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')

with open('test.txt', 'r') as rf:

    content = rf.read()
    matches = pattern.findall(content)

    open('iters.txt', 'w').close()
    for match in matches:
        with open('iters.txt', 'a') as wf:
            wf.write(match + '\n')

Upvotes: 0

Views: 1794

Answers (1)

Neil
Neil

Reputation: 14313

I rewrote the code a bit.

  1. I changed the regex to use {3} that way you don't have to repeat the same pattern so many times.
  2. I added os.path.exists to check to see if the file already exists. I think this is what you want, if not just remove that if. If the file already exists it does not write.
  3. I combined the two with's as you seem to be writing to a file and it doesn't make a ton of sense to keep on reopening the file to append a new line.
  4. I renamed pattern to ip_pattern just for readability sake, you can change it back if you want.

Code:

import re, os

ip_pattern = re.compile(r'(?:\d{1,3}\.){3}\d{1,3}')

if not os.path.exists("iters.txt"):
    with open('test.txt', 'r') as rf, open('iters.txt', 'a') as wf:
        content = rf.read()
        matches = ip_pattern.findall(content)
        for match in matches:
            wf.write(match + '\n')

Upvotes: 1

Related Questions