将目录中所有文件的 IP 地址替换为 Python 中的文件名

Replace IP addresses with filename in Python for all files in a directory

如果我知道关于 Python 的第一件事,我会通过参考其他已经回答的类似问题自己解决这个问题。

除此之外,我希望你能帮助我实现以下目标:

我希望用文件名本身替换所有出现的 IP 地址,在一个目录中,内联。

假设我所有的文件都在 D:\super\duper\directory\

文件没有任何扩展名,即示例文件名将是 "jb-nnnn-xy"。 即使文件中多次提到 IP 地址,我也有兴趣只替换看起来像这样的行(不带引号):

" TCPHOST = 72.163.363.25"

总的来说,该目录中有数千个文件,其中只有少数具有硬编码的 IP 地址。

兴趣线最终应如下所示:

" TCPHOST = jb-yyyy-nz"

其中 "jb-yyyy-nz" 是文件本身的名称

非常感谢您的宝贵时间和帮助!

编辑:只是我正在尝试的其他帖子中的一堆代码..

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)

请检查以下代码内联注释:

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) > 0:
           #If found update the line
            d = 'TCPHOST = '+str(fileinput.filename())
            print (d)
        else:
            #Otherwise keep as it is
            print (line.strip())

P.S: 假设该目录包含文件并且其中没有其他目录。否则,文件列表需要递归执行。