How to use win environment variable "pathlib" to save files?

Question:

I’m trying to use win environment variable like %userprofile%desktop with pathlib to safe files in different users PC.

But I’m not able to make it work, it keep saving in on the running script dir.

import pathlib
from datetime import datetime

a = r'%userprofile%desktoptest2' 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)
Asked By: Max

||

Answers:

Try:

import os
a = os.environ['USERPROFILE'] + r'desktoptest2'
# rest of script....
Answered By: salparadise

I use os.path.expandvars:

https://docs.python.org/3/library/os.path.html#os.path.expandvars

import os
os.path.expandvars(r"%UserProfile%Pictures")
'C:\Users\User\Pictures'
Answered By: XP1

pathlib does have Path.home(), which expands to the user’s home directory.

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"
Answered By: howdoicode