【问题标题】:Replace IP addresses with filename in Python for all files in a directory用 Python 中的文件名替换目录中所有文件的 IP 地址
【发布时间】:2016-10-13 11:49:40
【问题描述】:

如果我首先了解 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)

【问题讨论】:

  • 您是否尝试过自己编写代码?如果可以,请出示一下吗?
  • 用我正在尝试的代码更新了主帖...我的函数出现“预期的字符缓冲区对象”错误。当我反复运行它时,每次尝试它也会一个接一个地清空一个文件。

标签: python regex file replace substitution


【解决方案1】:

请使用 cmets inline 检查以下代码:

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: 假设目录包含文件,并且其中没有其他目录。否则,文件列表需要递归。

【讨论】:

  • 我在进入下一行之前按了 Enter。
  • 再一次......无论如何,我收到了这个错误:Traceback(最近一次调用最后一次):文件“resolver.py”,第 12 行,在 中,带有 fileinput.input(files =file_list,inplace=True) as f: AttributeError: FileInput instance has no attribute 'exit'
  • 嗯...似乎 Python 2.7.10 不允许文件输入的上下文管理器。通过关注this 解决了这个问题。我现在可以运行它,但它会重写整个文件而不是仅仅替换行......
  • 稍微调整了一下,现在它可以按要求工作了。谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
  • 2019-05-01
  • 2012-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-22
相关资源
最近更新 更多