Home
Go
Copy File
Updated Jan 27, 2025
Dot Net Perls
Copy file. In Go the os.Rename func moves a file from one location to another. But if we want to copy the file, we cannot just move it.
File
With ioutil, we can read in the contents of a file (with ReadAll). Then we can write the copy to a new location. This logic can be placed in a reusable func.
ioutil.WriteFile
Copy example. Here we have a main func that begins with 2 local variables. We must specify a valid input path (the source) and output path (the target).
func
Part 1 We open an input file with the os.Open func. We just ignore errors, but these could be checked.
Part 2 We read in the data from the file with ioutil.ReadAll. Again we just ignore errors.
Part 3 We call ioutil.WriteFile to write the data to a new location—the target location for the copy.
package main import ( "fmt" "io/ioutil" "os" ) func main() { inputPath := `C:\programs\file.txt` outputPath := `C:\programs\copy.txt` // Part 1: open input file. inputFile, _ := os.Open(inputPath) // Part 2: call ReadAll to get contents of input file. data, _ := ioutil.ReadAll(inputFile) // Part 3: write data to copy file. ioutil.WriteFile(outputPath, data, 0) fmt.Println("DONE") }
DONE
Notes, copying. When we want to copy a file, we cannot just call os.Rename as the original is deleted. Instead, we can use helpful methods from ioutil.
file.txt: 60 bytes copy.txt: 60 bytes
Summary. Often it is important to copy files for deployment of projects (like websites or applications). With the code here, we can copy files without deleting the originals.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 27, 2025 (edit).
Home
Changes
© 2007-2025 Sam Allen