Skip to main content
 首页 » 编程设计

python之使用python查找用户目录

2025年05月04日20think

所以我正在编写一个脚本来自动化我和我的队友所做的一些事情。我们有一个 git repo,这个脚本是供所有成员使用的。它有一个部分被硬编码为我的文件夹路径:C:/Users/jorge.padilla/etc...

我对 python 还是比较陌生,不熟悉所有不同的库。我基本上想将用户目录(即 jorge.padilla)变成一个非硬编码的变量,并且不需要接受用户输入,以便脚本将搜索当前用户目录并替换它。

下面是我正在编写的自动化脚本的一小段,用作示例。

import os, sys 
from pathlib import Path 
from enum import Enum 
 
#Global Variables 
PRODUCTS_FOLDER = "Products" 
APP_FOLDER = "App" 
DEV_BUILD = "ionic cordova build android" 
PROD_BUILD = "ionic cordova build android --release --prod" 
 
class BuildConfig(): 
    def __init__(self, start_path): 
        self.start_path = start_path 
 
    def getProductFolder(self): 
        return os.path.join(self.start_path, PRODUCTS_FOLDER) 
 
class BuildTypeEnum(Enum): 
    PROD = 1 
    DEV = 2 
 
def buildingApp(ConfigPath:BuildConfig, DEVvPROD:BuildTypeEnum): 
    path = ConfigPath.getProductFolder() 
    app_path = os.path.join(path, APP_FOLDER) 
    os.chdir(app_path) 
    if DEVvPROD == BuildTypeEnum.DEV: 
        os.system(DEV_BUILD) 
    elif DEVvPROD == BuildTypeEnum.PROD:  
        os.system(PROD_BUILD) 
    else: 
        print("Invalid input.") 
        return 
 
if __name__ == "__main__": 
    root_start_path = "C:/Users/jorge.padilla/Documents/" 
    build = BuildConfig(root_start_path) 
 
    buildType = None 
    buildTypeInput = input("Is this a dev or production build? (d/p): ") 
    if (buildTypeInput.lower() == 'd'): 
        buildType = BuildTypeEnum.DEV 
    elif (buildTypeInput.lower() == 'p'): 
        buildType = BuildTypeEnum.PROD 
    else: 
        print("Please specify if this is a development or production build.") 
        return 

我要为其执行此操作的主要变量是 root_start_path

请您参考如下方法:

你应该使用 pathlib (您导入但从未使用过的?):

import pathlib 
root_start_path = pathlib.Path.home()  # WindowsPath('C:/Users/jorge.padilla') 

它也适用于跨平台,它确实是处理文件路径的最佳方式 (IMO)

它甚至可以简化访问该路径中其他目录的语法:

root_start_path = pathlib.Path.home() / 'Documents'  # WindowsPath('C:/Users/jorge.padilla/Documents')