我需要能夠根據不同檔案中使用的路徑來確定檔案所在的位置。使用範例可能會更好:
這是目錄結構:
/ foo bar.txt text.txt bar main.go
在text.txt檔案中,bar.txt被./bar.txt
引用,它可以工作,但是如果我嘗試使用filepath.abs("從main.go找到<code>./bar.txt
的絕對路徑./bar.txt") 那麼它將回傳/bar/bar.txt
因為它假設.是目前工作目錄。
來自文件: abs 返迴路徑的絕對表示。如果路徑不是絕對路徑,它將與當前工作目錄連接以將其轉換為絕對路徑。
我的問題是如何在 ./bar.txt 時取得 ./bar.txt
的絕對路徑。與text.txt相關。
很抱歉這個問題可能太複雜,但我無法想出更好的方式來展示範例。
這個答案已經差不多了,但我設法修改它以適合我。
func getabs(path string, locationpath string) string { new_file_path := path new_abs_path := path if filepath.isabs(new_file_path) { new_abs_path = new_file_path } else { new_abs_path, _ = filepath.abs(filepath.join(locationpath, path)) fmt.println(new_abs_path, locationpath) } return new_abs_path }
只需將檔案的路徑新增至引用該檔案的檔案所在的目錄即可。
例如:
fmt.Println(getAbs("./bar.txt", "/foo")) //foo is the directory that text.txt is in which references bar.txt is in
以上是是否有一個函數可以從相對於另一個路徑返回絕對路徑?的詳細內容。更多資訊請關注PHP中文網其他相關文章!