6

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%\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)
martineau
  • 119,623
  • 25
  • 170
  • 301
Max
  • 117
  • 2
  • 7

3 Answers3

4

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'
XP1
  • 6,910
  • 8
  • 54
  • 61
4

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"
tbone
  • 7
  • 2
howdoicode
  • 779
  • 8
  • 16
  • While `pathlib` can handle the user's home directory, it doesn't have anything equivalent to the generic [`os.path.expandvars()`](https://docs.python.org/3/library/os.path.html#os.path.expandvars) that I am aware of however. – martineau Jun 30 '21 at 10:03
1

Try:

import os
a = os.environ['USERPROFILE'] + r'\desktop\test2'
# rest of script....
martineau
  • 119,623
  • 25
  • 170
  • 301
salparadise
  • 5,699
  • 1
  • 26
  • 32
  • 1
    I think the added literal string should be written like this `r'\desktop\test2'`. – martineau Nov 24 '18 at 10:14
  • 1
    salparadise: OK—did that after I verified it didn't working properly the way you had it. – martineau Nov 24 '18 at 20:47
  • If we want the home directory, then use `file_dir = pathlib.Path('~/Desktop/test2').expanduser()` and join it idiomatically as `file_path = file_dir / file_name`. pathlib will change it to use backslash on Windows. That said, Windows doesn't have the fixed Unix convention for the home directory. There are dozens of individually relocatable folders defined for each user. In this case "%USERPROFILE%\Desktop" is the default location for [`FOLDERID_Desktop`](https://learn.microsoft.com/en-us/windows/desktop/shell/knownfolderid#FOLDERID_Desktop), but it shouldn't be depended on. – Eryk Sun Nov 25 '18 at 02:24