在文件第 8 行写入文本

Write text at the 8th line in file

我想在第 8 行始终在多个文件中写评论。我试过了,但它只写在第一个文件中:

# insert comment to explain change
comment = now+":  Legal Litres changed to "+legalLitresTxt+"\n" 
commentCounter = 0

try:
    for i in mdcArray:


        line = ""

        Qqfile = glob.glob("/shares/web/vm3618/optiload/prog/MDC"+i+"/*/"+hexFile) 
        outFile = Qqfile[0]+".new"
        print i

        #read /shares/web/vm3618/optiload/prog/i/*/Hexfile
        for files in Qqfile:
            with open(files) as readFile:
                    content = readFile.readlines()

                    writer = open(outFile, 'w')

                    for line in content:
                       commentCounter += 1

                       if commentCounter == 8:
                           writer.write(comment)

有人可以解释为什么它只对数组中的第一个文件执行此操作吗?

您需要从0重新开始。 移动:

commentCounter = 0

前面
for line in content:

commentCounter = 0
for line in content:

您的代码应该如下所示(可以进行更多改进。此处并非出于教育目的。):

comment = now+":  Legal Litres changed to "+legalLitresTxt+"\n" 
try:
    for i in mdcArray:
        line = ""
        Qqfile = glob.glob("/shares/web/vm3618/optiload/prog/MDC"+i+"/*/"+hexFile) 
        outFile = Qqfile[0]+".new"
        print i
        #read /shares/web/vm3618/optiload/prog/i/*/Hexfile
        for files in Qqfile:
            with open(files) as readFile:
                    content = readFile.readlines()
                    writer = open(outFile, 'w')
                    commentCounter = 0
                    for line in content:
                        commentCounter += 1
                        if commentCounter == 8:
                            writer.write(comment)