Skip to content
Advertisement

Write to any users desktop in Python

Im new to Python so apologies if this is a basic question.

I have successfully created an exe file that writes to my specific desktop directory, but I am struggling to find a way to write to any users desktop directory. The idea being my exe file can be copied onto any user profile and work the same. Here is my code:

 file = open('C:\Users\user\Desktop\PC info.txt','w')

Could somebody help me adjust my code to work on any users desktop. Thank you in advance

Advertisement

Answer

You can get the username with the os module:

import os

username = os.getlogin()    # Fetch username
file = open(f'C:\Users\{username}\Desktop\PC info.txt','w')
file.write('Hello desktop')
file.close()
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement