-1

I would like to change the current work directory to the desktop without using os.chdir(path) since i want to use this code on different computer so the path will be different

  • 3
    Possible duplicate of [How to get Desktop location?](https://stackoverflow.com/questions/34275782/how-to-get-desktop-location) – Paritosh Singh Nov 22 '19 at 11:45
  • 2
    Use `os.chdir` but figure out the correct desktop path using the linked question. – Paritosh Singh Nov 22 '19 at 11:45
  • Sidenote though, usually you shouldn't *need* to change your working directories at all. Code that relies on current working directory can be fairly fragile. It may be a good idea to consider making your code work without affecting working directories by always using absolute paths. – Paritosh Singh Nov 22 '19 at 11:47

2 Answers2

1

To get the desktop location you can use os.path.expanduser("~/Desktop"). This should work both in Windows and Linux, regardless of actual directories where the desktop is kept. To change directory to the current desktop you should do something like this:

os.chdir(os.path.expanduser("~/Desktop"))
Artur
  • 973
  • 1
  • 14
  • 29
0

There is multi able ways to do it :

import os
os.path.join(os.environ["HOMEPATH"], "Desktop")

Output:

'\Users\Admin\Desktop'

os.path.join(os.path.expanduser("~"), "Desktop")

Output:

'C:\Users\Admin\Desktop'

os.path.normpath(os.path.expanduser("~/Desktop"))

Output:

'C:\Users\Admin\Desktop'

Ahmed Soliman
  • 1,662
  • 1
  • 11
  • 16