我想在文件中特定行的特定列插入一个字符串。
假设我有一个文件 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/