2

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

MrShaun
  • 43
  • 1
  • 5

4 Answers4

5

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()
figbeam
  • 7,001
  • 2
  • 12
  • 18
2

You could use os.getlogin with an f-string to insert the username to the file path:

import os

with open(fr'C:\Users\{os.getlogin()}\Desktop\PC info.txt', 'w') as f:
    # do something with f

But, a much better cleaner way nowadays would be to use pathlib:

import pathlib

with open(pathlib.Path.home() / "Desktop/PC info.txt", "w"):
    # do something with f

Also, it's always advisable to use a context manager (with open(...) as f) to handle files, so that the filehandler gets closed even if an exception occurs.

ruohola
  • 21,987
  • 6
  • 62
  • 97
0

If you are using Python3.5+, you can use the following to get the path to the current user's home directory:

import os
import sys
from pathlib import Path

def main():
    home = str(Path.home())
    path = os.path.join(home, "filename.txt")
    with open(path, "w") as f:
        f.write("HelloWorld")

if __name__ == '__main__':
    main()
Andrew St P
  • 524
  • 1
  • 5
  • 13
0

Is this what you are looking for?

username = "MrShaun"
filename = "C:\\Users\\{0}\\Desktop\\PC info.txt".format(username)

file = open(filename, 'w')

In this example, filename would be: "C:\Users\MrShaun\Desktop\PC info.txt"

Obviously, you would probably want to build a structure around it, for example asking the user for input of a username and assigning that to the variable username.

Read more about formatting strings in Python here

Jonas
  • 41
  • 5
  • You probably want to use "username = os.getlogin()" instead, it fetches the username of the currently active user. – Jonas Apr 30 '19 at 18:10