如何将临时文件(图像、txt等)添加到临时目录,然后在Python中访问它们?

如何将临时文件(图像、txt等)添加到临时目录,然后在Python中访问它们?,python,Python,我想创建一个名为workdir的临时目录,在里面我想写一些文件,添加一些图像,然后读取这些文件和图像。但我不明白我怎么能做到这一点。我是python新手,只知道基本知识,所以如果有人能帮助我,我将不胜感激 这是我从stackoverflow中选取的一个例子,因为它是被选中的答案,但它对我不起作用 import tempfile import os with tempfile.TemporaryDirectory() as workdir: print('tmp dir name',

我想创建一个名为workdir的临时目录,在里面我想写一些文件,添加一些图像,然后读取这些文件和图像。但我不明白我怎么能做到这一点。我是python新手,只知道基本知识,所以如果有人能帮助我,我将不胜感激

这是我从stackoverflow中选取的一个例子,因为它是被选中的答案,但它对我不起作用

import tempfile
import os

with tempfile.TemporaryDirectory() as workdir:

    print('tmp dir name', workdir)

    # write file to tmp dir
    fout = open(os.path.join(workdir,'file.txt'), 'w')
    fout.write('test write')
    fout.close()

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

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

    
    for file in os.listdir(workdir):
        print('searching in directory')
        print(file)
这是不正确的:

# working with the file is fine
fin = open(workdir + 'file.txt', 'U')
workdir
没有尾随
/
,因此它试图打开的文件路径是
/tmp/tmp4r1zdpqmfile.txt
(如错误中所述),而不是预期的
/tmp/tmp4r1zdpqm/file.txt
。使用
os.path.join()
(与前面写入文件时一样)允许目录和文件的平台无关组合


此外,不推荐使用
'U'
文件选项。使用类似于
'w'
'r'
,或
'r+'
的内容。有关更多详细信息,请参阅。

当您说“它不适合我”时,您能提供更多详细信息吗?是否引发异常等?这是我正在获取file.txt位置/tmp/tmp4r1zdpqmlala.fasta/home/aqsa/aqsa/practice.py的错误:16:DeprecationWarning:'U'模式已弃用fin=open(workdir+'file.txt','U')回溯(最后一次调用):file/home/aqsa/aqsa/practice.py,第16行,fin=open(workdir+'file.txt','U')FileNotFoundError:[Errno 2]没有这样的文件或目录:'/tmp/tmp4r1zdpqmfile.txt'您的代码缩进是否与您发布的代码缩进相同?目前,您正在退出“workdir”上下文管理器存在于中,并且我想象临时目录在退出时被删除。我已经更正了缩进,只是在这里它是错误的