-1

I have a code that makes a folder:

if not os.path.exists('C:\\Users\\MYNAME\\Documents\\Myfiles):
     os.chdir('C:\\Users\\MYNAME\\Documents')
     os.mkdir('Myfiles')

I want this to be able to run on any computer, so how can I get the default user without asking and doing something like:

DefaultUser = input('What is the default user for this PC?: ')
if not os.path.exists('C:\\Users\\' + DefaultUser + '\\Documents\\Myfiles'):
    os.chdir('C:\\Users\\' + DefaultUser + '\\Documents')
    os.mkdir('Myfiles')

EDIT: By default user, I mean the one currently running the program.

3 Answers3

0

You can try the following to first get the username using getpass and then use it in the path using a placeholder %s. I tried it on my Mac and it returned the correct username.

import getpass
Name = getpass.getuser()
print (Name) # To confirm that it gives the correct username

if not os.path.exists('C:\\Users\\%s\\Documents\\Myfiles' %Name):
    os.chdir('C:\\Users\\%s\\Documents' %Name)
    os.mkdir('Myfiles')
Sheldore
  • 37,862
  • 7
  • 57
  • 71
0

Since you're already using os, make use of the expanduser() method in path:

import os
curdir = os.path.expanduser('~/Documents')
# 'C:\\Users\\me/Documents'
newdir = 'Myfiles'
if not os.path.exists(os.path.join(curdir, newdir)):
    os.chdir(curdir)
    os.mkdir(newdir)
r.ook
  • 13,466
  • 2
  • 22
  • 39
0

Since the answer is about the process owner

import os
import psutil

# get the PID
pid = os.getpid()

# get the username
username = psutil.Process(pid).username

Untested, but should work on Windows and Linux

user3142459
  • 630
  • 5
  • 18