在python文件的开头和结尾添加行

2024-06-03 00:20:55 发布

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

很好,我有以下代码:

numList = [6, 7, 8, 10, 15, 18, 31, 35, 51, 54]

with open('/home/user/test.nft') as f:
    lines = f.readlines()

for i, l in enumerate(lines): 
    for num in numList:
        if l.startswith('add rule ip filter vlan_%d' %num):
            if "oifname bond1.%d" %num in l:
                f = open('inet-filter-chain-vlan%d_in.nft' %num, 'a')
            else:
                f = open('inet-filter-chain-vlan%d_out.nft' %num, 'a')

            f.write(l)
            f.close()
            break

我想在if:inet筛选器链vlan%d中生成的文件的开头和结尾添加一行_输入.nft和inet筛选器链vlan%d_输出.nft. 你知道吗

例如,inet-filter-chain-vlan20的内容_输入.nft文件应为:

Custom line for file 20

......content...........

Custom line for file 20


Tags: 文件inchainforifcustomlineopen
1条回答
网友
1楼 · 发布于 2024-06-03 00:20:55

您需要缓存要写入的文件。你知道吗

这可以用一套

为什么不再次使用with open(...) as f:?你知道吗

fileset = set()
for i, l in enumerate(lines): 
    for num in numList:
        if l.startswith('add rule ip filter vlan_%d' %num):
            in_out = 'in' if "oifname bond1.%d" %num in l else 'out'
            filename = 'inet-filter-chain-vlan%d_%s.nft' % (num, in_out)
            with open(filename, 'a') as f:
                # the first time we open a file, output the custom line
                if filename not in fileset:
                    custom_string="Custom line for %s\n" % filename
                    f.write(custom_string)
                    fileset.add(filename)
                f.write(l)
            break
# now we need to write the final line in each file
for filename in fileset:
    with open(filename, 'a') as f:
        custom_string="Custom line for %s\n" % filename
        f.write(custom_string)

有其他方法可以做到这一点,但这很简单,并且不会使文件保持打开状态,这会增加经常打开和关闭文件(每行)的开销,但不会潜在地打开许多文件。你知道吗

如果您想保持文件打开以执行写操作,我建议使用裸打开,使用dict(按文件名键入)存储文件引用,然后在写入最后一行后关闭它们。它应该看起来像:

filedict = {}
for i, l in enumerate(lines): 
    for num in numList:
        if l.startswith('add rule ip filter vlan_%d' %num):
            in_out = 'in' if "oifname bond1.%d" %num in l else 'out'
            filename = 'inet-filter-chain-vlan%d_%s.nft' % (num, in_out)
                # the first time we open a file, output the custom line
                f = filedict.get(filename)
                if f is None:
                    custom_string="Custom line for %s\n" % filename
                    f = open(filename, 'a')
                    f.write(custom_string)
                    filedict[filename] = f
                f.write(l)
            break
# now we need to write the final line in each file
for filename, f in filedict:
    custom_string="Custom line for %s\n" % filename
    f.write(custom_string)
    f.close()

相关问题 更多 >