【问题标题】:How to get temp directory in Python with a non-ascii windows username?如何使用非 ascii windows 用户名在 Python 中获取临时目录?
【发布时间】:2021-06-13 04:34:53
【问题描述】:

简单的问题,但找不到答案(可能是谷歌搜索词错误?)。

我的 Windows 10 临时目录是

C:\Users\Aurélien\AppData\Local\Temp

注意我的用户名:Aurélien 包含一个不兼容标准 ascii 的 é。但是,这是我的名字。

在 VS 2019 中使用交互式 Python 3.8 时,我输入以下代码:

import tempfile
print(tempfile.gettempdir())

结果是:

C:\Users\AURLIE~1\AppData\Local\Temp

如何获得正确的格式答案?

预期

C:\Users\Aurélien\AppData\Local\Temp

谢谢。

【问题讨论】:

  • @Gravity 和@Yuval.R 我在前额研究中被踩到了,是的,这与我的观点非常相似,除了据我所知(所以也许我不知道),这是 python 2.7 的问题。当我自己在 python 3.x (3.8) 下运行时,我尝试了解决方法(使用unicode())。但它在 Python 3.x 中不可用,因为如果我是正确的,在 3.x 中 unicode 应该是标准行为吗?我也尝试使用from builtins import str 作为 unicode() 的 python 3 替代品,但没有更改结果路径。

标签: python-3.x


【解决方案1】:

这是我可怕的“解决方法”,它现在是一个答案,但我不会将其勾选为已接受的答案。 如果你有更好的,我很乐意等待。

from pathlib import Path
def _getutempdir():
  usr = 'Users'
  h = Path.home()
  tmp = Path(tempfile.gettempdir())
  lh = list(h.parts)
  ltmp = list(tmp.parts)
  if (usr in lh and usr in ltmp):
      hui = lh.index(usr)
      tmpui = ltmp.index(usr)
      if ((len(lh)> hui+1) and (len(ltmp)>tmpui+1)):
          ltmp[tmpui+1] = lh[hui+1]
          tmp = Path(*ltmp)
  return tmp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    相关资源
    最近更新 更多