-2

I'm trying to move a file but it won't work. It keeps giving the error "Errno 2: File or directory does not exist". The code is shown below

import shutil

original = '%userprofile%/Desktop/Test'
New = '%userprofile%/Desktop/Test2'

shutil.move(original, New)

if anyone has any advice on how to solve this please help me.

SpicySoap
  • 3
  • 3
  • 1
    I would have to assume environment variable expansion is not supported by `shutil`... – Aaron Apr 06 '22 at 16:51

2 Answers2

1

You can use os.path.expandvars to expand the %userprofile% variable and the resultant path can be passed into the shutil.move API.

>>> help(os.path.expandvars)
Help on function expandvars in module ntpath:

expandvars(path)
    Expand shell variables of the forms $var, ${var} and %var%.

    Unknown variables are left unchanged.

ie,

shutil.move(os.path.expandvars(original), os.path.expandvars(New))
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
0

If %userprofile% is the only variable you need, it can be done with pathlib.Path.expanduser as such:

import shutil
from pathlib import Path

original = Path('~/Desktop/Test').expanduser()
New = Path('~/Desktop/Test2').expanduser()

shutil.move(original, New)
Aaron
  • 10,133
  • 1
  • 24
  • 40