本文主要介绍Python中,将字符串写入文本文件(.txt,.ini,config等)中指定行和列的位置和删除文本文件中指定行方法,以及相关示例代码。

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()

相关文档:

Python(Python2 Python3)读写配置文件(ConfigParser)方法

Python PyCrypto(PyCryptodome) ASE实现对文件加密和解密方法