python-tempfile和listdir奇怪的行为

python-tempfile和listdir奇怪的行为,python,Python,今天我遇到了一个非常奇怪的行为,请看下面的代码片段: import tempfile from os import listdir from os.path import join, abspath with tempfile.TemporaryDirectory() as tmp_folder: with open(join(tmp_folder, 'test.pdf'), 'a'): pass pdfs = [abspath(x) for x in list

今天我遇到了一个非常奇怪的行为,请看下面的代码片段:

import tempfile
from os import listdir
from os.path import join, abspath

with tempfile.TemporaryDirectory() as tmp_folder:
    with open(join(tmp_folder, 'test.pdf'), 'a'):
        pass
    pdfs = [abspath(x) for x in listdir(tmp_folder)] # What the hell happens here?
    print(tmp_folder)
    print(pdfs)
输出:

> C:\Users\vincenzo\AppData\Local\Temp\tmp2b5j1yyd
> ['C:\\Users\\vincenzo\\Cloud\\Hobby\\Programmi\\Python\\scripts\\Contabilità\\test.pdf']
你能解释一下发生了什么事情,以及我如何获得我所期望的C:\Users\vincenzo\AppData\Local\Temp\tmp2b5j1yyd\test.pdf吗?

listdir只返回文件名,没有目录前缀。因此,abspath无法知道文件名来自临时目录,它返回当前工作目录中的绝对路径

使用join以文件名加入tmp_文件夹

pdfs = [join(tmp_folder, x) for x in listdir(tmp_folder)]

成功了,谢谢!