•  


Go by Example: File Paths

Go by Example : File Paths

The filepath package provides functions to parse and construct file paths in a way that is portable between operating systems; dir/file on Linux vs. dir\file on Windows, for example.

package
 main
import
 (

    "fmt"

    "path/filepath"

    "strings"

)
func
 main
()
 {

Join should be used to construct paths in a portable way. It takes any number of arguments and constructs a hierarchical path from them.

    p
 :=
 filepath
.
Join
(
"dir1"
,
 "dir2"
,
 "filename"
)

    fmt
.
Println
(
"p:"
,
 p
)

You should always use Join instead of concatenating / s or \ s manually. In addition to providing portability, Join will also normalize paths by removing superfluous separators and directory changes.

    fmt
.
Println
(
filepath
.
Join
(
"dir1//"
,
 "filename"
))

    fmt
.
Println
(
filepath
.
Join
(
"dir1/../dir1"
,
 "filename"
))

Dir and Base can be used to split a path to the directory and the file. Alternatively, Split will return both in the same call.

    fmt
.
Println
(
"Dir(p):"
,
 filepath
.
Dir
(
p
))

    fmt
.
Println
(
"Base(p):"
,
 filepath
.
Base
(
p
))

We can check whether a path is absolute.

    fmt
.
Println
(
filepath
.
IsAbs
(
"dir/file"
))

    fmt
.
Println
(
filepath
.
IsAbs
(
"/dir/file"
))
    filename
 :=
 "config.json"

Some file names have extensions following a dot. We can split the extension out of such names with Ext .

    ext
 :=
 filepath
.
Ext
(
filename
)

    fmt
.
Println
(
ext
)

To find the file’s name with the extension removed, use strings.TrimSuffix .

    fmt
.
Println
(
strings
.
TrimSuffix
(
filename
,
 ext
))

Rel finds a relative path between a base and a target . It returns an error if the target cannot be made relative to base.

    rel
,
 err
 :=
 filepath
.
Rel
(
"a/b"
,
 "a/b/t/file"
)

    if
 err
 !=
 nil
 {

        panic
(
err
)

    }

    fmt
.
Println
(
rel
)
    rel
,
 err
 =
 filepath
.
Rel
(
"a/b"
,
 "a/c/t/file"
)

    if
 err
 !=
 nil
 {

        panic
(
err
)

    }

    fmt
.
Println
(
rel
)

}
$
 go run file-paths.go
p: dir1/dir2/filename
dir1/filename
dir1/filename
Dir(p): dir1/dir2
Base(p): filename
false
true
.json
config
t/file
../c/t/file

Next example: Directories .

- "漢字路" 한글한자자동변환 서비스는 교육부 고전문헌국역지원사업의 지원으로 구축되었습니다.
- "漢字路" 한글한자자동변환 서비스는 전통문화연구회 "울산대학교한국어처리연구실 옥철영(IT융합전공)교수팀"에서 개발한 한글한자자동변환기를 바탕하여 지속적으로 공동 연구 개발하고 있는 서비스입니다.
- 현재 고유명사(인명, 지명등)을 비롯한 여러 변환오류가 있으며 이를 해결하고자 많은 연구 개발을 진행하고자 하고 있습니다. 이를 인지하시고 다른 곳에서 인용시 한자 변환 결과를 한번 더 검토하시고 사용해 주시기 바랍니다.
- 변환오류 및 건의,문의사항은 juntong@juntong.or.kr로 메일로 보내주시면 감사하겠습니다. .
Copyright ⓒ 2020 By '전통문화연구회(傳統文化硏究會)' All Rights reserved.
 한국   대만   중국   일본