Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在文件的第8行写入文本_Python_Linux_File Handling - Fatal编程技术网

Python 在文件的第8行写入文本

Python 在文件的第8行写入文本,python,linux,file-handling,Python,Linux,File Handling,我想在几个文件中写一条评论,总是在第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

我想在几个文件中写一条评论,总是在第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
开始。 移动:

在前面

for line in content:
i、 e

您的代码应该是这样的(可能会有更多的改进。这里不是为了教育目的而做的):

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)