替换For循环中的文件行

2024-09-29 22:24:44 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个包含多个MAC地址的不同MAC地址符号的文件。我想替换从参数输入中解析的一个MAC地址的所有匹配符号。到目前为止,我的脚本生成了我需要的所有符号,可以循环遍历文本的行,并显示必须更改的行。你知道吗

import argparse, sys

parser = argparse.ArgumentParser()
parser.add_argument("-f", "--filename")
parser.add_argument("-m",  "--mac_address")
args = parser.parse_args()

mac = args.mac_address #In this case 00:1a:e8:31:71:7f

colon2 = mac #00:1a:e8:31:71:7f
dot2 = colon2.replace(":",".") # 00.1a.e8.31.71.7f
hyphen2 = colon2.replace(":","-") # 00-1a-e8-31-71-7f
nosymbol = colon2.replace(":","") # 001ae831717f
colon4 = ':'.join(nosymbol[i:i+4] for i in range(0, len(nosymbol), 4)) # 001a:e831:717f 
dot4 = colon4.replace(":",".") # 001a.e831.717f
hyphen4 = colon4.replace(":","-") # 001a-e831-717f


replacethis = [colon2,dot2,hyphen2,dot4,colon4,nosymbol,hyphen4]
with open(args.filename, 'r+') as f:
    text = f.read()
    for line in text.split('\n'):
        for n in replacethis:
            if line.replace(n, mac) != line:
                print line + '\n has to change to: \n'line.replace(n,mac)
            else:
                continue

如果文件如下所示:

fb:76:03:f0:67:01

fb.76.03.f0.67.01

fb-76-03-f0-67-01

001a:e831:727f

001ae831727f

fb76.03f0.6701

001ae831727f

fb76:03f0:6701

001a.e831.727f

fb76-03f0-6701

fb7603f06701

应更改为:

fb:76:03:f0:67:01

fb.76.03.f0.67.01

fb-76-03-f0-67-01

00:1a:e8:31:71:7f

00:1a:e8:31:71:7f

fb76.03f0.6701

00:1a:e8:31:71:7f

fb76:03f0:6701

00:1a:e8:31:71:7f

fb76-03f0-6701

fb7603f06701

我正在努力将包含更改的MAC地址符号的新行写回到替换前一行的文件中。你知道吗

有办法吗?你知道吗


Tags: parserfbmac地址line符号argsreplace
1条回答
网友
1楼 · 发布于 2024-09-29 22:24:44

一个简单的方法来实现你所要求的,你可以添加一行来存储你得到的最终值,然后包括另一个'WITHOPEN'语句来将它写入一个新文件。你知道吗

replacethis = [colon2, dot2, hyphen2, dot4, colon4, nosymbol, hyphen4]
final_values =[]
with open(args.filename, 'r+') as f:
    text = f.read()
    for line in text.split('\n'):
        for n in replacethis:
            if line.replace(n, mac) != line:
                print line + '\n has to change to: \n'line.replace(n,mac)
                final_values.append(line.replace(n, mac)
            else:
                continue
                final_values.append(line)
with open(new_file_name, ‘w’) as new_f:
    new_f.write(final_values)

请注意,如果new\u file\u name=旧文件名,则会覆盖原始文件。你知道吗

我希望这能回答你的问题。你知道吗

相关问题 更多 >

    热门问题