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>

<p>Please check the below code with comments inline:</p>

<pre><code>import os
import re
import fileinput
#Get the file list from the directory
file_list = [f for f in os.listdir("C:\\Users\\dinesh_pundkar\\Desktop\\demo")]

#Change the directory where file to checked and modify
os.chdir("C:\\Users\\dinesh_pundkar\\Desktop\\demo")

#FileInput takes file_list as input 
with fileinput.input(files=file_list,inplace=True) as f:
    #Read file line by line
    for line in f:
        d=''
        #Find the line with TCPHOST
        a = re.findall(r'TCPHOST\s*=\s*\d+\.',line.strip())
        if len(a) &gt; 0:
           #If found update the line
            d = 'TCPHOST = '+str(fileinput.filename())
            print (d)
        else:
            #Otherwise keep as it is
            print (line.strip())
</code></pre>

<p><strong>P.S:</strong> <em>Assumed the directory contains file and it does not have other directory inside it. Otherwise, file listing need to do recursively.</em> </p>

python regex file replace substitution