简体   繁体   English

创建一个临时目录以存储用于计算的文件

[英]Creating a temp directory for storing files used in calculation

A python script downloads 2 tables from a database, does some calculations and creates a new one, and uploads it. python脚本从数据库中下载2个表,进行一些计算并创建一个新表,然后将其上传。 There are intermediate files involved and to store all the files I create a folder called “temp” in the current working directory. 其中涉及中间文件,为了存储所有文件,我在当前工作目录中创建了一个名为“ temp”的文件夹。 Before the program exits it deletes temp. 在程序退出之前,它会删除温度。 This doesn't work very well because 这不是很好,因为

  1. If there already is a folder named temp it will be deleted 如果已经有一个名为temp的文件夹,它将被删除
  2. If the program crashes before the last step of deleting temp, the next time the program runs it crashes because files with the same name exist from the previous execution. 如果程序在删除temp的最后一步之前崩溃,则该程序下次运行时将崩溃,因为前一次执行中存在具有相同名称的文件。

I imagine this is a relatively common scenario. 我认为这是一个相对常见的情况。 How is it normally handled? 通常如何处理?

there is a tempfile module just for this 有一个为此的临时文件模块

import tempfile
new_dir = tempfile.mkdtemp() #makes a new temp folder guaranteed to be unique(in the os-specific temp location)
...
os.remove(new_dir)

really I dont think you even need to remove the new_dir as it will automagically be gone on next reboot usually(*i think) 真的,我认为您甚至不需要删除new_dir,因为通常在下次重新启动时它会自动消失(*我认为)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM