LoginSignup
4
1

More than 5 years have passed since last update.

[Go] ファイルの拡張子を変更する

Last updated at Posted at 2017-10-08

path/filepath を使って安全に。

package main

import (
    "fmt"
    "path/filepath"
)

func replaceExt(filePath, from, to string) string {
    ext := filepath.Ext(filePath)
    if len(from) > 0 && ext != from {
        return filePath
    }
    return filePath[:len(filePath)-len(ext)] + to
}

/* Example */
func main() {
    filePath := "inputDir/input.csv"

    fmt.Println(filePath)
    // => inputDir/input.csv

    filePath = replaceExt(filePath, ".csv", ".json")
    fmt.Println(filePath)
    // => inputDir/input.json

    filePath = replaceExt(filePath, ".json", "")
    fmt.Println(filePath)
    // => inputDir/input

    fmt.Println(replaceExt("inputDir/input", ".csv", ".json"))
    // => inputDir/input

    fmt.Println(replaceExt("inputDir/input.rcsv.csv", ".csv", ".json"))
    // => inputDir/input.rcsv.json
}
4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1