1、写入文本文件中指定位置
def update(filename, lineno, column, text): fro = open(filename, "rb") current_line = 0 while current_line < lineno - 1: fro.readline() current_line += 1 seekpoint = fro.tell() frw = open(filename, "r+b") frw.seek(seekpoint, 0) # read the line we want to update line = fro.readline() chars = line[0: column-1] + text + line[column-1:] while chars: frw.writelines(chars) chars = fro.readline() fro.close() frw.truncate() frw.close() if __name__ == "__main__": update("file.txt", 4, 13, "History ")
2、删除文本文件中指定行
def removeLine(filename, lineno): fro = open(filename, "rb") current_line = 0 while current_line < lineno: fro.readline() current_line += 1 seekpoint = fro.tell() frw = open(filename, "r+b") frw.seek(seekpoint, 0) # read the line we want to discard fro.readline() # now move the rest of the lines in the file # one line back chars = fro.readline() while chars: frw.writelines(chars) chars = fro.readline() fro.close() frw.truncate() frw.close()
相关文档: