我正在制作一个小程序来跟踪程序的执行流程。我有一些文件有源代码,有些文件没有源代码。对于在没有源代码的文件中发生的调用,我试图对它们进行计数,并将这个数字调整到输出行的末尾。
据我所知,我从末尾定位光标3个字符,然后当我将output写到myfile时,它应该已经覆盖了前面的3个字符。但是当我查看文件时,这3个字符只是被追加到末尾。
with open("C:\\Windows\\Temp\\trace.html", "a+") as myfile:
if hasNoSource and not fileHasChanged:
myfile.seek(-3,2)
output = line
else:
self.noSourceCallCount = 0
myfile.write(output)
return self.lineHook发布于 2015-09-11 01:57:23
"a+“模式是为追加模式打开的,并且通过()所做的任何更改都将在下一个write()之前重置。使用"r+“模式。
发布于 2015-09-11 03:15:19
带有inplace选项的文件输入模块允许您修改您的文件,但是如果所有的文件都崩溃了,一定要进行备份。
import fileinput,sys,re
line_count=0
for line in open(my_file):
line_count+=1 # count total lines in file
f=fileinput.input(my_file,inplace=True)
for line in f:
line_count-=1 #when iterating through every line decrement line_count by 1
if line_count==0:
line=re.sub("...$",<replacement>,line) #use regex to replace first three characters in the last line
sys.stdout.write(line) #print line to sys.stdout which will automatically make the changes to this line in file.
else:
sys.stdout.write(line)https://stackoverflow.com/questions/32514227
复制相似问题