2015-09-11 30 views
0

我正在制作一个小程序来跟踪程序的执行流程。我有一些文件有源代码,有些则没有。对于没有源代码的文件中发生的调用,我试图对它们进行计数,并将该数字粘贴到输出行的末尾。如何编辑文件的最后几个字符?

从我的理解中我定位光标从最后3个字符,然后当我写outputmyfile时,它应该覆盖前面的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 

回答

1

“a +”模式对追加模式打开,seek()的任何更改都会被下一个write()重置。使用“r +”模式。与就地选项

+0

其实我读了确切的线,但理解它的意思是重置光标之后一个写,而不是之前。 –

0

的FileInput模块允许您修改文件,但一定要做好备份,如果所有的地狱冲出重围

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) 
+0

注意是你输入你想要的角色的地方 – repzero

相关问题