path to Desktop on Windows without having to know username

Viewed 937

I'm use py2exe to create a .exe file so that someone without Python on their computer can run a script. Because I'm creating an alias (shortcut) of the .exe file, I need to hardcode the path to the folder containing the files that the python script targets. I also need to make sure that it will work on anyone's desktop (regardless of username) and work in a folder called Reports. I tried using the following line of code but I got an invalid syntax error:

cwd = r"os.path.expanduser("~/Desktop/Reports")"

I wondered if anyone could provide any advice to help solve this?

Thanks in advance

3 Answers

Maybe this help you

desktop="c:\\users\\{}\\Desktop".format(os.getenv("username"))

This works on my Windows installation:

>>> import os
>>> desktop = os.path.expanduser('~') + '\Desktop'
>>> print(desktop)
C:\Users\MY_USERNAME\Desktop
>>> cwd = os.path.expanduser('~\Desktop\Reports')
>>> print(cwd)
C:\Users\MY_USERNAME\Desktop\Reports

As a standalone script:

import os
import csv2xlsx 


cwd = os.path.expanduser('~\Desktop\Reports')
print(cwd)

csv2xlsx.main(cwd + "\Report.csv", cwd + "\Report.xlsx")

Output:

C:\Users\MY_USERNAME\Desktop\Reports

I'm not the best with python, but I know that if you substitute this in your code, you'll get your Desktop directory.

os.environ["HOMEPATH"]

It might not work but substitute it in your code and try it out. Good luck!

Related