如何将默认用户插入文件路径 python

How to insert the default user into a filepath python

我有一个制作文件夹的代码:

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

我希望它能够 运行 在任何计算机上,所以我怎样才能在不询问和执行类似以下操作的情况下获得默认用户:

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')

编辑:默认用户,我指的是当前正在 运行 正在运行该程序的用户。

您可以尝试以下操作,首先使用 getpass 获取用户名,然后使用占位符 %s 在路径中使用它。我在 Mac 上试过了,它返回了正确的用户名。

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')

由于您已经在使用 os,请使用 path 中的 expanduser() 方法:

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)

因为答案是关于流程所有者的

import os
import psutil

# get the PID
pid = os.getpid()

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

未经测试,但应该适用于 Windows 和 Linux