在fi的第8行写下文本

2024-09-30 20:36:50 发布

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

我想写一个评论在几个文件总是在第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)

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


Tags: 文件toinwebforlinecommentoutfile
1条回答
网友
1楼 · 发布于 2024-09-30 20:36:50

你需要再次从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)

相关问题 更多 >