【问题标题】:How to insert the default user into a filepath python [duplicate]如何将默认用户插入文件路径python [重复]
【发布时间】:2018-10-30 17:24:14
【问题描述】:

我有一个创建文件夹的代码:

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

编辑:默认用户是指当前运行程序的用户。

【问题讨论】:

  • 你不能用%HOMEDRIVE%%HOMEPATH%吗?
  • 你可以使用 pathlib 中的Path.home()

标签: python default filepath


【解决方案1】:

您可以尝试以下操作,首先使用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')

【讨论】:

    【解决方案2】:

    既然您已经在使用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)
    

    【讨论】:

      【解决方案3】:

      因为答案是关于进程所有者

      import os
      import psutil
      
      # get the PID
      pid = os.getpid()
      
      # get the username
      username = psutil.Process(pid).username
      

      未经测试,但应该可以在 Windows 和 Linux 上运行

      【讨论】:

        猜你喜欢
        • 2011-05-17
        • 2014-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多