首页 > 解决方案 > python - tempfile 和 listdir 奇怪的行为

问题描述

今天我遇到了一个很奇怪的行为,请看这个小代码片段:

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我的预期?

标签: python

解决方案


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

用于join()加入tmp_folder文件名。

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

推荐阅读