如何使用win环境变量“pathlib”保存文件?

Max*_*Max 6 python windows environment-variables pathlib

我正在尝试使用 win 环境变量来%userprofile%\desktop保护pathlib不同用户 PC 中的文件。

但我无法让它工作,它一直保存在运行脚本目录中。

导入路径库
从日期时间导入日期时间

a = r'%userprofile%\desktop\test2' b = 'test' def path(path_name, f_name): date = datetime.now().strftime("%d%m-%H%M%S") file_name = f'{f_name}--{date}.xlsx' file_path = pathlib.Path(path_name).joinpath(file_name) file_dir = pathlib.Path(path_name) try: file_dir.mkdir(parents=True, exist_ok=True) except OSError as err: print(f"Can't create {file_dir}: {err}") return file_path path(a, b)

Run Code Online (Sandbox Code Playgroud)

how*_*ode 6

pathlib确实有Path.home(),它扩展到用户的主目录。

from pathlib import Path
print(Path.home())    # On Windows, it outputs: "C:\Users\<username>"

# Build a path to Desktop
desktop = Path.home() / "Desktop"
print(desktop)    # On Windows, it outputs: "C:\Users\<username>\Desktop"
Run Code Online (Sandbox Code Playgroud)


sal*_*ise 1

尝试:

import os
a = os.environ['USERPROFILE'] + r'\desktop\test2'
# rest of script....
Run Code Online (Sandbox Code Playgroud)