python tempfile在哪里写文件?

2024-04-29 08:38:37 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中,您可以创建一个tempfile,如下所示:

tempfile.TemporaryFile()

然后你可以写信给它。GNU/Linux系统中的文件写在哪里?我似乎在/tmp目录或任何其他目录中都找不到它。

谢谢你


Tags: 文件gnu目录linux系统tempfiletmptemporaryfile
3条回答

在贝壳上试试这个

    $python
>>> import tempfile
    >>>tempfile.gettempdir()

'/var/folders/5r/lxh8g5ln7zg43_l_3t0j7b1c0000gn/T'

这将显示python正在使用的实际临时路径。

你可以选择试试这个。(这将产生与上述相同的结果)

    $python
>>> import tempfile
    >>>tempfile.tempdir
'/var/folders/5r/lxh8g5ln7zg43_l_3t0j7b1c0000gn/T'

查看文件句柄上的.name确实是查看文件存在位置的一种方法。在^{}(在*NIX系统上)的情况下,您将看到<fdopen>,表示打开的文件句柄,但没有相应的目录项。如果要保留到基础文件的链接,则需要使用^{}


如果要控制临时文件的位置,请查看dir参数:

^{}使用^{},这允许使用dir参数设置目录:

If dir is specified, the file will be created in that directory; otherwise, a default directory is used. The default directory is chosen from a platform-dependent list, but the user of the application can control the directory location by setting the TMPDIR, TEMP or TMP environment variables.

调用^{} function

Return the directory currently selected to create temporary files in.

如果要影响临时文件的创建位置,可以通过将^{} value设置为不同的目录来更改临时文件的创建位置。引用文档,如果该值为None,则规则如下:

If tempdir is unset or None at any call to any of the above functions, Python searches a standard list of directories and sets tempdir to the first 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 RiscOS, the directory named by the Wimp$ScrapDir environment variable.
    • 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.

相关问题 更多 >