我想在文件中特定行的特定列插入字符串,而不读取和重写整个文件。
假设我有一个文件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?
通过添加字符串History
在第 4 行第 13 列。
目前,我读取文件的每一行并将字符串添加到指定位置。
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()
但我觉得我应该能够简单地将行添加到文件中,而不必读取和重写entire file.
这可能是下面 SO 线程的重复
在 Python 中从大文件中删除行的最快方法 https://stackoverflow.com/questions/2329417/fastest-way-to-delete-a-line-from-large-file-in-python
上面讲的是删除,这只是一种操作,而你的更多的是修改。所以代码会像下面这样更新
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 ")
在一个大文件中,直到需要更新的行号才进行修改是有意义的,假设您有 10K 行的文件,并且需要在 9K 处进行更新,您的代码将加载所有内容9K
内存中不必要的数据行。您拥有的代码仍然可以工作,但不是最佳方法
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)