Replace IP addresses with filename in Python for all files in a directory
<p>If I knew the first thing about Python, I'd have figured this out myself just by referring to other similar questions that were already answered. </p>

<p>With that out of the way, I'm hoping you can help me achieve the following:  </p>

<p>I'm looking to replace all occurrences of IP addresses with the file name itself, in a directory, inline.</p>

<p>Let's say all my files are in <code>D:\super\duper\directory\</code></p>

<p>Files don't have any extension, i.e., a sample file name will be <em><code>"jb-nnnn-xy"</code></em>.
Even if there are multiple mentions of IP address in the file, I'm interested in replacing only the line that looks like this (without quotes):</p>

<p><code>" TCPHOST  = 72.163.363.25"</code></p>

<p>So overall, there are thousands of files in the directory, of which only few have hard-coded IP addresses. </p>

<p>And the line of interest should finally look like this:</p>

<p><code>" TCPHOST  = jb-yyyy-nz"</code></p>

<p>where <em><code>"jb-yyyy-nz"</code></em> is the name of the file itself</p>

<p>Thank you very much for your time and help!</p>

<p>EDIT: Just a mish mash of code from other posts that I'm trying out..</p>

<pre><code>from __future__ import print_function
import fnmatch
import os 
from fileinput import FileInput
import re

ip_addr_regex = re.compile(r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b')
def find_replace(topdir, text):
    for dirpath, dirs, files in os.walk(topdir, topdown=True):
        files = [os.path.join(dirpath, filename) for filename in files]
        for line in FileInput(files, inplace=True):
                print(line.replace(text, str(filename)))

find_replace(r"D:\testmulefew",ip_addr_regex)
</code></pre>