简体   繁体   English

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

[英]Add line at the beginning and end of a file in python

Good, I have the following code: 好,我有以下代码:

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

I want to add a line at the beginning and end of the generated files in the if: inet-filter-chain-vlan% d_in.nft and inet-filter-chain-vlan% d_out.nft. 我想在if:inet-filter-chain-vlan%d_in.nft和inet-filter-chain-vlan%d_out.nft中生成的文件的开头和结尾添加一行。

For example, the contents of the inet-filter-chain-vlan20_in.nft file should be: 例如,inet-filter-chain-vlan20_in.nft文件的内容应该是:

Custom line for file 20 文件20的自定义行

......content........... ......内容...........

Custom line for file 20 文件20的自定义行

You need to cache which files you are writing to. 您需要缓存要写入的文件。

This can be done in a simple manner with a set, 这可以通过一套简单的方式完成,

Why not use with open(...) as f: again too? 为什么不再使用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)

There are other ways to do this, but this is simple and doesn't leave the files open, which has an overhead in opening and closing the files often (for each line) but doesn't potentially open many files. 还有其他方法可以做到这一点,但这很简单,不会让文件保持打开状态,这会经常打开和关闭文件(对于每一行),但不会打开很多文件。

If you want to keep the files open for write performace, I suggest using bare opens, use a dict (keyed by filename) to store the file references, then close them after writing the final line. 如果你想保持文件打开以进行写性能,我建议使用裸开,使用dict(用文件名键控)来存储文件引用,然后在写完最后一行后关闭它们。 It should look something like: 它应该看起来像:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM