'How to save a file to users desktop

I want to be able to save a file to any users desktop running a script. Its currently set up to save on my desktop

    df1.to_csv('C:\\Users\\myusername\\OneDrive\\Desktop\\file.csv', index=False)

How do I save it to any users desktop running the script?



Solution 1:[1]

With import os you can use os.environ.get('USER') or os.environ.get('USERNAME') to get the username of the current user.

Then simply substitute the username from the path to the desktop.

Solution 2:[2]

A modern way (Python 3.5+) would be

import pathlib

file_path = pathlib.Path.home() / "Desktop" / "file.csv"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KevinIssaDev
Solution 2 Jussi Nurminen