Python 在文件的第8行写入文本
我想在几个文件中写一条评论,总是在第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
# 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)