更新:使用ShadowRanger的答案。它更短且更健壮。
对于后代:
读取文件的最后N个字节,然后向后搜索换行符。
#!/usr/bin/env pythonwith open("test.txt", "wb") as testfile: testfile.write('n'.join(["one", "two", "three"]) + 'n')with open("test.txt", "r+b") as myfile: # Read the last 1kiB of the file # we could make this be dynamic, but chances are there's # a number like 1kiB that'll work 100% of the time for you myfile.seek(0,2) filesize = myfile.tell() blocksize = min(1024, filesize) myfile.seek(-blocksize, 2) # search backwards for a newline (excluding very last byte # in case the file ends with a newline) index = myfile.read().rindex('n', 0, blocksize - 1) # seek to the character just after the newline myfile.seek(index + 1 - blocksize, 2) # read in the last line of the file lastline = myfile.read() # modify last_line lastline = "Brand New Line!n" # seek back to the start of the last line myfile.seek(index + 1 - blocksize, 2) # write out new version of the last line myfile.write(lastline) myfile.truncate()


