Inc*_*tic 12 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?
Run Code Online (Sandbox Code Playgroud)
我想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()
Run Code Online (Sandbox Code Playgroud)
但我觉得我应该能够简单地将行添加到文件中,而无需读取和重写整个文件.
这可能是下面 SO 线程的重复
上面讲的是删除,这只是一种操作,而你的更多的是修改。所以代码会像下面这样更新
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 ")
Run Code Online (Sandbox Code Playgroud)
在大文件中,直到需要更新的行号才进行修改是有意义的,假设您有 10K 行的文件,并且需要在 9K 行进行更新,您的代码将不必要地加载9K内存中的所有数据行。您拥有的代码仍然可以工作,但不是最佳方法
| 归档时间: |
|
| 查看次数: |
2670 次 |
| 最近记录: |