文件将在哪里创建?

Where will the file be created?

import tempfile

storage_path = os.path.join(tempfile.gettempdir(), 'storage.data')
    with open(STORAGE_PATH, 'w') as f:
    f.write(data)

在哪个目录下创建文件?在那里可以看到它还是看不见它?

this link...

列表是:

  • TMPDIR环境变量命名的目录
  • TEMP环境变量命名的目录
  • TMP环境变量命名的目录
  • 特定于平台的位置:

    • 在 Windows 上,目录 C:\TEMPC:\TMP\TEMP\TMP
    • 在所有其他平台上,目录依次为 /tmp/var/tmp/usr/tmp
    • 作为最后的手段,当前工作目录。

样本来自 mac os :

/var/folders/4x/2rjwjpyn1pn9_0t1r5_m8blr0000gn/T/storage.data

当您通过查找器转到目录时,文件应该就在那里。至于Windows可能是隐藏的,相信你可以解锁。

当前没有正在创建的文件。查看 tempfile documentation 以查找有关模块功能的更多信息,例如 .gettempdir():

Python searches a standard list of directories to find one which the calling user can create files in. The list is:

  1. The directory named by the TMPDIR environment variable.

  2. The directory named by the TEMP environment variable.

  3. The directory named by the TMP environment variable.

  4. A platform-specific location: On Windows, the directories C:\TEMP, C:\TMP, \TEMP, and \TMP, in that order. On all other platforms, the directories /tmp, /var/tmp, and /usr/tmp, in that order.

  5. As a last resort, the current working directory.

您只创建了一个字符串,仅此而已。

tempfile.gettempdir() functionreturns一个字符串:

Return the name of the directory used for temporary files

这只是一个名字。如果您需要知道系统上的位置但不想逐步执行文档中概述的规则,请打印它;有 3 个环境变量和另外 3 个标准位置可供测试,以查看当前用户有权在何处创建文件。

接下来,os.path.join()接受字符串并输出一个字符串。没有在磁盘上创建任何内容来构建这些字符串。这将取决于您是否实际对该字符串执行某些操作(例如调用 os.makedirs()open())将创建什么。

如果您对该字符串使用普通 open() 调用,则会在其他进程可见的 tempfile.gettempdir() 位置创建一个常规文件。

如果您需要安全地创建临时文件,以便攻击者无法访问文件或影响文件的创建位置,请使用tempfile.TemporaryFile() constructor or the tempfile.mkstemp() function;在 UNIX 系统上,这将导致目录中不再列出一个文件(该文件存在但不能被其他进程打开)。但是,它将在 tempfile.gettempdir() 位置创建,因此它将用尽该目录所在的相关磁盘分区上的磁盘 space。