假设我有一个包含多个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:1408米
00:1A:E8:31:71:1408米
fb76.03f0.6701
00:1A:E8:31:71:1408米
fb76:03f0:6701
00:1A:E8:31:71:1408米
fb76-03f0-6701
fb7603f06701
我正在努力将包含已更改的MAC地址表示法的新行写回替换上一行的文件。
有办法做到这一点吗?
答案 0 :(得分:0)
实现您所要求的一种简单方法可以添加一行来存储您获得的最终值,然后包含另一个“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 =您的旧文件名,则会覆盖原始文件。
我希望能回答你的问题。