在我的tempfile.temporary目录()用于Python3

2024-03-28 12:20:26 发布

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

我在使用Python3的tempfile库时遇到了困难。在

我需要在临时目录中写一个文件,并确保它在那里。我使用的第三方软件工具有时会失败,所以我不能直接打开文件,我需要先用“while循环”或其他方法验证它是否在那里,然后再打开它。所以我需要搜索tmp_dir(使用操作系统列表目录()或等效物)。在

如能提供具体帮助/解决方案和一般帮助,我们将不胜感激。在

谢谢。在

小样本代码:

import os
import tempfile


with tempfile.TemporaryDirectory() as tmp_dir:

    print('tmp dir name', tmp_dir)

    # write file to tmp dir
    fout = open(tmp_dir + 'file.txt', 'w')
    fout.write('test write')
    fout.close()

    print('file.txt location', tmp_dir + 'lala.fasta')

    # working with the file is fine
    fin = open(tmp_dir + 'file.txt', 'U')
    for line in fin:
        print(line)

    # but I cannot find the file in the tmp dir like I normally use os.listdir()
    for file in os.listdir(tmp_dir):
        print('searching in directory')
        print(file)

Tags: 文件theinimport目录txtosdir
1条回答
网友
1楼 · 发布于 2024-03-28 12:20:26

这是预期的,因为临时目录名不以路径分隔符结尾(os.sep斜杠反斜杠在许多系统上)。所以文件是在错误的级别创建的。在

tmp_dir = D:\Users\T0024260\AppData\Local\Temp\tmpm_x5z4tx
tmp_dir + "file.txt"
=> D:\Users\T0024260\AppData\Local\Temp\tmpm_x5z4txfile.txt

取而代之,join在临时目录中获取文件的两个路径:

^{pr2}$

注意,fin = open(tmp_dir + 'file.txt', 'U')找到了预期的文件,但是它在创建tmp_dir的同一目录中找到了它。在

相关问题 更多 >