How to Copy a File in Go

1. Introduction

Copying files is a routine task in software development, often required for data backup, duplication, or migration processes. Go's standard library provides the necessary tools to copy files in a concise and efficient manner. This blog post will demonstrate how to copy a file in Go.

2. Program Steps

1. Open the source file using os.Open.

2. Create the destination file with os.Create.

3. Use the io.Copy function to perform the actual copying of data.

4. Handle any potential errors during the process.

5. Close both the source and destination files.

3. Code Program

To copy a file in Go, you need to open the source file, create the destination file, and then use the io.Copy function to copy the data. This operation reads the content from the source file and writes it to the destination file.

Here is the complete Go program to demonstrate how to copy a file:
package main

import (

func main() {
	// The source and destination file paths
	sourcePath := "source.txt"
	destinationPath := "destination.txt"

	// Step 1: Open the source file
	sourceFile, err := os.Open(sourcePath)
	if err != nil {
		fmt.Println("Error opening source file:", err)
	defer sourceFile.Close() // Ensure file is closed after copying is done

	// Step 2: Create the destination file
	destinationFile, err := os.Create(destinationPath)
	if err != nil {
		fmt.Println("Error creating destination file:", err)
	defer destinationFile.Close() // Ensure file is closed after copying is done

	// Step 3: Use io.Copy to copy the contents from source to destination
	_, err = io.Copy(destinationFile, sourceFile)
	if err != nil {
		fmt.Println("Error copying file:", err)

	// If no error occurred, print a success message
	fmt.Printf("File copied successfully from %s to %s\n", sourcePath, destinationPath)


File copied successfully from source.txt to destination.txt


1. package main - The package declaration for the Go program.

2. import statements - Importing the fmt, io, and os packages for output formatting, I/O operations, and file system handling respectively.

3. sourcePath and destinationPath hold the paths to the source and destination files.

4. os.Open is used to open the source file for reading.

5. os.Create is used to create the destination file. If the file already exists, it will be truncated.

6. defer is used to ensure both source and destination files are closed after the copying process, regardless of where the function exits.

7. io.Copy takes the destination file and source file, and copies the data from the source to the destination.

8. An error during the copy process is handled and printed. Otherwise, a success message is printed.

9. The output confirms that the file has been copied from source.txt to destination.txt.