[英]how to replace strings with path objects in python?
我有以下字典:
config = {
'base_dir': Path(__file__).resolve(strict=True).parent.absolute(),
'app_dir': '<base_dir>/app'
}
我想用<base_dir>
的值替換 < <base_dir>
所以我這樣做了:
for key, value in config.items():
if type(value) == str:
vars_to_replace = re.findall(r'\<.+\>',value)
for var in vars_to_replace:
config[key] = value.replace(var,config[var[1:-1]])
當前收到錯誤: TypeError: replace() argument 2 must be str, not WindowsPath
如果我用str()
包裝我的config[var[1:-1]]
。 它消除了錯誤,但我丟失了 WindowsPath,現在 app_dir 變成了一個字符串。 我想將 object 保留為 WindowsPath。
value
是一個字符串,因此您嘗試使用字符串的replace
方法,該方法將兩個字符串作為 arguments。 如果要將 app_dir 的值更改為路徑app_dir
,則必須構建路徑 object 並將當前值('/app')替換為該 object。 您可以通過多種方式執行此操作,這是一種:
app_dir
中的標記替換為該字符串,然后將新路徑轉換為 Path object這看起來像:
for key, value in config.items():
if type(value) == str:
vars_to_replace = re.findall(r'\<*[.+]\>',value)
for var in vars_to_replace:
new_path = value.replace(var, str(config[var[1:-1]]))
config[key] = Path(new_path)
另一種方法是使用類似path.join()
到 append 到路徑 object 的東西:
path_addition = value.replace(var, "")
new_path_object = config[var].join(path_addition) # <-- might need to adjust this depending on the exact Path class you are using
config[key] = new_path_object
希望這些幫助,快樂編碼!
我會說提取base_dir
和app
然后用它們構建一個路徑:
for key, value in config.items():
if isinstance(value, str):
# parent_str will be "base_dir" and name_str will be "app"
parent_str, name_str = re.fullmatch(r"\<(.+)?>/(\w+)", value).groups()
parent_path = config[parent_str]
config[key] = parent_path / Path(name_str)
我沒有使用 for 循環,假設一個值中只有一個這樣的匹配是可能的。 如果不是這種情況,您可以使用finditer
包裝一個 for 循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.