簡體   English   中英

從For循環替換文件中的行

[英]Replace lines in file from For Loop

假設我有一個文件,其中包含多個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地址表示法的新行寫回到替換前一行的文件中。

有沒有辦法做到這一點?

實現要求的一種簡單方法是,可以添加一行存儲所獲得的最終值,然后再添加另一條“ with open”語句以將其寫入新文件。

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_file_name =您的舊文件名,則將覆蓋原始文件。

我希望能回答您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM