Home
Map
Copy FileUse ioutil to copy a file by reading in its contents and then writing to a new file.
Golang
This page was last reviewed on Dec 20, 2022.
Copy file. In Golang 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.
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
A 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.
C#VB.NETPythonGolangJavaSwiftRust
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2023 Sam Allen.