gpt4 book ai didi

python - 重命名 python 临时文件

转载 作者:行者123 更新时间:2023-12-02 06:49:36 25 4
gpt4 key购买 nike

重命名以下临时文件的方法是什么

pdf = render_me_some_pdf() #PDF RENDER
f = tempfile.NamedTemporaryFile()
f.write(pdf)
f.flush()

我读过一些关于 os.rename 的内容,但我现在不知道如何应用它

最佳答案

The best way is copying the file and letting python delete the temporary one when it's closed:

我实际上认为你最好使用os.link:

with tempfile.NamedTemporaryFile(dir=os.path.dirname(actual_name)) as f:
f.write(pdf)
os.link(f.name, actual_name)

这使用os.link创建到临时文件的硬链接(hard link),该文件临时文件自动删除后仍会保留。

这段代码有几个优点:

  • 我们使用 tempfile 对象作为上下文管理器,因此我们不需要担心显式关闭它。
  • 由于我们正在创建文件的硬链接(hard link),而不是复制它,我们不需要担心磁盘空间或时间消耗复制大文件。
  • 由于我们不复制数据,因此不需要调用 f.flush()。文件关闭时会自动刷新。

关于python - 重命名 python 临时文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10547859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com