You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何tempfile.gettempdir()返回路径与实际临时文件夹不符?

问题解答

为什么临时目录路径看起来不一样?

C:\Users\JEFFSA~1\AppData\Local\Temp是C:\Users\JeffSandor\AppData\Local\Temp的Windows短文件名(8.3格式),两者指向同一个文件夹。Windows会自动给长文件名生成这类短别名,用于兼容旧DOS/16位程序,所以tempfile.gettempdir()返回的路径是正确的,只是显示形式不同而已。

为什么会报FileNotFoundError?

你仅通过os.path.join拼接了HDD目录的路径,但并未实际创建这个目录。直接尝试写入该目录下的Path.txt时,系统找不到对应的文件夹,就会抛出这个错误。

修复代码:

先创建HDD目录,再写入文件:

import os
import tempfile

temp = os.path.join(tempfile.gettempdir(), "HDD")
# 创建目录,exist_ok=True表示目录已存在时不报错
os.makedirs(temp, exist_ok=True)
print(temp)

# 推荐用os.path.join拼接文件路径,适配不同系统的路径分隔符
file_path = os.path.join(temp, "Path.txt")
with open(file_path, "w") as fh:
    fh.write(path)

内容的提问来源于stack exchange,提问作者jeffinter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 21:33:10