好,我目前有以下代码:
n = 0
with open('/home/user/test.filter') as f:
lines = f.readlines()
for l in lines:
if lines[n].startswith('-A vlan_8'):
if "-o bond1.8" in lines[n]:
f = open('vlan8.filter_in', 'a')
f.write(l)
else:
f = open('vlan8.filter_out', 'a')
f.write(l)
if lines[n].startswith('-A vlan_10'):
if "-o bond1.10" in lines[n]:
f = open('vlan10.filter_in', 'a')
f.write(l)
else:
f = open('vlan10.filter_out', 'a')
f.write(l)
if lines[n].startswith('-A vlan_15'):
if "-o bond1.15" in lines[n]:
f = open('vlan15.filter_in', 'a')
f.write(l)
else:
f = open('vlan15.filter_out', 'a')
f.write(l)
# [...]
n = n + 1
我想过用一些累加器或列表来优化它,以免使脚本如此广泛。有什么建议吗?
答案 0 :(得分:2)
当然可以。保持这些数字的列表如下:
numList = [8, 10, 15, ...]
现在,您只需要一个小字符串格式化。
with open('/home/user/test.filter') as f:
lines = f.readlines()
for i, l in enumerate(lines): # I've used enumerate to eliminate n but really you don't need it
for num in numList:
if l.startswith('-A vlan_%d' %num):
if "-o bond1.%d" %num in l:
f = open('vlan%d.filter_in' %num, 'a')
else:
f = open('vlan%d.filter_out' %num, 'a')
f.write(l)
f.close()
break
答案 1 :(得分:0)
我认为您希望使代码更清晰,而不是更快。如果是这样,也许这会奏效:
import re
parameter_re = re.compile(r'^-A vla_(\d+).*')
with open('data.csv') as f:
lines = f.readlines()
for line in lines:
# Match required parameter
match = parameter_re.match(line)
# Skip line if it doesn't match the required parameter
if not match:
continue
# Extract number from parameter
number = int(match.group(1))
# Create output parameter string
output_str = '-o bond1.%d' % number
# Select correct filename to save the line
if output_str in line:
output_filename = 'vlan%d.filter_in' % number
else:
output_filename = 'vlan%d.filter_out' % number
# Write the line to the correct file
with open(output_filename, 'a') as f:
f.write(line)
如果你想让它更短(我不推荐,最好是可读):
import re
with open('data.csv') as f:
lines = f.readlines()
for line in lines:
match = re.match(r'^-A vla_(\d+).*', line)
if not match:
continue
number = int(match.group(1))
if '-o bond1.%d' % number in line:
output_filename = 'vlan%d.filter_in' % number
else:
output_filename = 'vlan%d.filter_out' % number
with open(output_filename, 'a') as f:
f.write(line)