【发布时间】:2020-10-09 13:13:02
【问题描述】:
我查看了类似的问题,但没有找到解决问题的方法。
我试图在文本文件的第二行插入一行文本,但是我不想打开和关闭文本文件,因为我在大量文件上运行此代码,并且不要'不想让它慢下来。我找到了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 权限问题?
【问题讨论】:
标签: python python-3.x temporary-files shutil