python - 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
我的预期?
解决方案
listdir()
只返回文件名,它们没有目录前缀。因此abspath()
无法知道文件名来自临时目录,它返回当前工作目录中的绝对路径。
用于join()
加入tmp_folder
文件名。
pdfs = [join(tmp_folder, x) for x in listdir(tmp_folder)]
推荐阅读
- reactjs - StateManagement 工具与原生 useState
- flutter - Flutter webview:ssl_client_socket_impl 和 Uncaught SecurityError 错误
- sql-server - 如何在 Azure 数据仓库(突触)中授予架构级别权限?
- c# - 卸载几个参考后出现未知错误
- python - 如何在python中将数据框的列名从字符串转换为元组?
- python - 如何在数组中查找非字符串索引
- android - 使用 Hilt 注入 CoroutineWorker
- swift - 如何快速在两个段中显示一个tableview数据
- python - 如何在'def'中过滤python中的数字
- c++ - IShellFolder::GetDisplayNameOf 返回乱码