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

时间:2017-06-07 10:28:34

标签: 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-filter-chain-vlan%d_in.nft和inet-filter-chain-vlan%d_out.nft中的生成文件的开头和结尾添加一行。

例如,inet-filter-chain-vlan20_in.nft文件的内容应为:

  

文件20的自定义行

     

......内容...........

     

文件20的自定义行

1 个答案:

答案 0 :(得分:0)

您需要缓存要写入的文件。

这可以通过一套简单的方式完成,

为什么不再使用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)

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

还有其他方法可以做到这一点,但这很简单,不会让文件保持打开状态,这会经常打开和关闭文件(对于每一行),但不会打开很多文件。< / p>

如果你想保持文件打开以进行写性能,我建议使用裸开,使用dict(用文件名键控)来存储文件引用,然后在写完最后一行后关闭它们。它应该看起来像:

library(rtweet)
r <- search_tweets("#rstats")
r[c(3:5,8),c("mentions_screen_name", "text")]
#     mentions_screen_name                                                                                                                                         text
# 3               DataCamp      RT @DataCamp: Algorithmic Trading in R, tutorial &amp; tips here - U5KQzE8rJI #Algotrading #rstats PNxQ8OSquX
# 4                   <NA>                  Cheat Sheet of Machine Learning and Python (and Math) Cheat Sheets | ymj4bu8pCB | #rstats #python #datascience
# 5              Rbloggers                                             RT @Rbloggers: How to Install R Ubuntu 16.04 Xenial xNk51T5E6F #rstats #DataScience
# 8 DataScienceLA earlconf RT @DataScienceLA: Slides for my talk at @earlconf #EARLConf2017 are here xYDWKnR3tM #rstats #machinelearning U9k…