簡體   English   中英

在Python中為局部變量使用相對路徑

[英]Using a relative path for a local variable in Python

我在Python腳本中有一個本地變量,該變量使用本地C:\\<User> folder的路徑創建臨時文件:

 Output_Feature_Class = "C:\\Users\\<User>\\Documents\\ArcGIS\\Default.gdb\\Bnd_"

但是,我希望能夠與其他人共享此腳本,而不必為使用它的每個人都必須對文件路徑進行硬編碼。 我基本上希望它轉到相同的文件夾,但<insert their User Name>示例: C:\\\\TBrown\\\\Documents\\\\ArcGIS\\Default.gdb\\\\Bnd_ 我似乎不能只使用

 Output_Feature_Class = "..\\Documents\\ArcGIS\\Default.gdb\\Bnd_"

上班。 我有什么想念的嗎?

為什么不使用getpass而不是要求他們輸入用戶名?

例如,獲取用戶名:

import getpass
a = getpass.getuser()
Output_Feature_Class = "C:\\Users\\" + a + "\\Documents\\ArcGIS\\Default.gdb\\Bnd_"

如果您在Windows上工作(並且僅適用於Windows),則pywin模塊可以找到文檔的路徑:

from win32com.shell import shell, shellcon

a = shell.SHGetFolderPath(0, shellcon.CSIDL_PERSONAL, None, 0)

Output_Feature_Class = "{}\\ArcGIS\\Default.gdb\\Bnd_".format(a)

但這不是跨平台的。 感謝martineau提供此解決方案,請參閱查找用戶的“我的文檔”路徑以查找文檔路徑。

答案與@Simon相同,但使用字符串格式將其壓縮一點,而不是嘗試將字符串連接在一起:

import getpass

Output_Feature_Class = "C:\\Users\\%s\\Documents\\ArcGIS\\Default.gdb\\Bnd_" % getpass.getuser()

正如@Matteo Italia指出的那樣,沒有任何內容可以保證用戶配置文件位於c:\\users ,或者使用用戶名調用用戶配置文件目錄。 因此,也許通過獲取用戶的主目錄並從那里建立路徑來解決該問題將更為有利:

from os.path import expanduser
Output_Feature_Class = "%s\\Documents\\ArcGIS\\Default.gdb\\Bnd_" % expanduser("~")

更新資料

正如@Matteo Italia再次指出的那樣,默認情況下,有時候Documents目錄位於其他位置。 這可能有助於找到路徑DocumentsMy Documents文件夾中:參考( 鏈接

from win32com.shell import shell
df = shell.SHGetDesktopFolder()
pidl = df.ParseDisplayName(0, None, "::{450d8fba-ad25-11d0-98a8-0800361b1103}")[1]

Output_Feature_Class = "%s\\ArcGIS\\Default.gdb\\Bnd_" % shell.SHGetPathFromIDList(pidl)

為什么不使用Windows%TEMP%環境變量,而不是將臨時文件存儲在您選擇的位置(可能存在或可能不存在)中? 如果未設置%TEMP%,則許多軟件將無法工作。

import os

def set_temp_path(*args):
    if os.name is 'nt':
        temp_path = os.getenv('TEMP')
        if not temp_path:
            raise OSError('No %TEMP% variable is set? wow!')
        script_path = os.path.join(temp_path, *args)
        if not os.path.exists(script_path):
            os.makedirs(script_path)
        return script_path
    elif os.name is 'posix':
        #perform similar operation for linux or other operating systems if desired
        return "linuxpath!"
    else:
        raise OSError('%s is not a supported platform, sorry!' % os.name)

您可以將此代碼用於此腳本或任何其他腳本的任意臨時文件結構:

my_temp_path = set_temp_path('ArcGIS', 'Default.gdb', 'Bnd_')

它將為您創建所有需要的目錄,並返回路徑以在腳本中進一步使用。

'C:\\Users\\JSmith\\AppData\\Local\\Temp\\ArcGIS\\Default.gdb\\Bnd_'

如果您打算支持多個平台,那么這當然是不完整的,但是在Linux上使用全局/tmp或/ var/temp路徑應該很簡單。

要獲取用戶的主目錄,可以使用os.path.expanduser獲取用戶的主目錄。

Output_Feature_Class = os.path.join(os.path.expanduser('~'), "Documents\\ArcGIS\\Default.gdb\\Bnd_")

正如其他人提到的,在執行此操作之前,請考慮這是否是這些文件的最佳位置。 臨時文件應位於OS約定為臨時文件保留的位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM