python - 如何在文件中的行和列位置插入文本?

标签 python python-3.x

我想在文件中特定行的特定列插入一个字符串。

假设我有一个文件 file.txt

How was the English test?
How was the Math test?
How was the Chemistry test?
How was the test?

我想将最后一行更改为 How was the History test?,方法是在第 4 行第 13 列添加字符串 History

目前我读取文件的每一行并将字符串添加到指定位置。

with open("file.txt", "r+") as f:
    # Read entire file
    lines = f.readlines()

    # Update line
    lino = 4 - 1
    colno = 13 -1
    lines[lino] = lines[lino][:colno] + "History " + lines[lino][colno:]

    # Rewrite file
    f.seek(0)
    for line in lines:
        f.write(line)
    f.truncate()
    f.close()

但我觉得我应该能够简单地将行添加到文件中,而不必读取和重写整个文件。

最佳答案

这可能是下面 SO 线程的副本

Fastest Way to Delete a Line from Large File in Python

上面讲的是delete,只是一个操作,你的更多的是修改。所以代码会像下面这样更新

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

在一个大文件中,直到需要更新的 lineno 之前不进行修改是有意义的,假设您有 10K 行的文件并且需要在 9K 处进行更新,您的代码将加载所有 9K内存中不必要的数据行。您拥有的代码仍然可以工作,但不是最佳方式

关于python - 如何在文件中的行和列位置插入文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49742962/

相关文章:

python - 如何使用 tvl1 opencv 函数计算光流

python - 交换 linspace 图的轴

python-3.x - 如何在 AWS EMR 中将 Jupyter 笔记本设置为 Python3 而不是 Python2.7

python-3.x - 如何使用 VS Code for Windows 在 WSL (Ubuntu) 中查找和激活虚拟环境

python-3.x - 使用 Python 3.2 CType 调用 CreateRemoteThread 时出现 Error_Invalid_Parameter 错误 57

python - 在哪里可以了解如何在 python3 中处理音频 IO 和编解码器?

Python argparse 与多个组中的相同参数互斥

python - 根据不同的列列表从 DataFrame 中选择行的有效方法

python - 递归函数背后的心态

r - 更新 Pandas 后无法导入 rpy2.robjects "ValueError: The system "%s"不受支持。"