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:
JavaScript
x
2
1
file = open('C:\Users\user\Desktop\PC info.txt','w')
2
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:
JavaScript
1
7
1
import os
2
3
username = os.getlogin() # Fetch username
4
file = open(f'C:\Users\{username}\Desktop\PC info.txt','w')
5
file.write('Hello desktop')
6
file.close()
7