问题描述
我正在尝试在文本文件的第二行中插入一行文本,但是由于要在大量文件上运行此代码,因此我不想打开和关闭文本文件,并且不想放慢脚步。我找到了this的类似问题的答案,并且一直在努力解决;我在这里使用tempfile创建一个工作正常的临时文件:如下所示:
from pathlib import Path
from shutil import copyfile
from tempfile import NamedTemporaryFile
sourcefile = Path("Path\to\source").resolve()
insert_lineno = 2
insert_data = "# Mean magnitude = " + str(mean_mag)+"\n"
with sourcefile.open(mode="r") as source:
destination = NamedTemporaryFile(mode="w",dir=str(sourcefile.parent))
lineno = 1
while lineno < insert_lineno:
destination.file.write(source.readline())
lineno += 1
destination.file.write(insert_data)
while True:
data = source.read(1024)
if not data:
break
destination.file.write(data)
# Finish writing data.
destination.flush()
# Overwrite the original file's contents with that of the temporary file.
# This uses a memory-optimised copy operation starting from Python 3.8.
copyfile(destination.name,str(sourcefile))
# Delete the temporary file.
destination.close()
倒数第二个命令copyfile(destination.name,str(sourcefile))
不起作用,我正在得到
[Errno 13]权限被拒绝:'D:\ My_folder \ Subfolder \ tmp_s570_5w'
我认为问题可能在于我无法从临时文件中复制文件,因为该文件当前处于打开状态,但是如果我关闭了该临时文件,它将被删除,因此我也无法在复制之前将其关闭。
编辑:当我在Linux上运行代码时,我没有得到任何错误,因此一定是某种Windows权限问题?
解决方法
尝试一下:
sourcefile = Path("Path\to\source").resolve()
insert_lineno = 2
insert_data = "# Mean magnitude = " + str(mean_mag)+"\n"
with sourcefile.open(mode="r") as source:
with NamedTemporaryFile(mode="w",dir=str(sourcefile.parent)) as destination:
lineno = 1
while lineno < insert_lineno:
destination.file.write(source.readline())
lineno += 1
destination.file.write(insert_data)
while True:
data = source.read(1024)
if not data:
break
destination.file.write(data)
# Finish writing data.
destination.flush()
# Overwrite the original file's contents with that of the temporary file.
# This uses a memory-optimised copy operation starting from Python 3.8.
copyfile(destination.name,str(sourcefile))
# Delete the temporary file.
destination.close()