[Golang] Move File to Another Directory


The shell command mv is used to move files in Linux system. I want to move file directly in Go, so I searched golang os.Move [1] and found that os.Rename is the method I need. Let's try to see how it works.

I have one file and one directory as follows:

.
├── hello.txt
└── testdir/

I want to move hello.txt to testdir/, so I write the following code:

package main

import (
      "os"
)

func main() {
      err := os.Rename("hello.txt", "testdir/")
      if err != nil {
              panic(err)
      }
}

Seems reasonable, because this is how we use mv command under Linux shell. When I run the Go code, panic happened:

panic: rename hello.txt testdir/: file exists

So we cannot just put the name of testdir/ in the new path of os.Rename. We have to specify the whole new path, including the file name:

package main

import (
      "os"
)

func main() {
      err := os.Rename("hello.txt", "testdir/hello.txt")
      if err != nil {
              panic(err)
      }
}

And we get the result as expected:

.
└── testdir/
    └── hello.txt

Tested on: Ubuntu Linux 17.10, Go 1.10


References:

[1]
[2]func Rename - os - The Go Programming Language
[3]