Go File Handling
File handling is one of the most common operations in Go—reading configuration, writing logs, and data persistence all rely on it. Go's standard library provides a concise yet powerful set of file I/O interfaces, covering scenarios from single reads and writes to stream processing.
There are 5 core packages related to file handling, each with its own role:
Version note:
ioutilThe package was deprecated in Go 1.16, and its functionality has been migrated toos(such asos.ReadFile、os.WriteFile) andio(such asio.ReadAll). New code should directly useosandiothe package.
1. File creation
os.Create Create a new file. If the file already exists, it will be truncated (contents cleared). The returned file object must be closed to release system resources:
Example
package
main
import
(
"log"
"os"
)
func
main
()
{
// os.Create creates a file (clears it if it already exists)
file
,
err
:=
os
.
Create
(
"test.txt"
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
defer
file
.
Close
()
// defer ensures the file is closed when the function ends
// Write content to verify successful creation
file
.
WriteString
(
"File created successfully\n"
)
log
.
Println
(
"File created successfully"
)
}
defer file.Close()is a best practice for Go file operations.deferensures that even if a panic occurs in subsequent code, the file will be properly closed, avoiding file descriptor leaks.
2. Opening and closing files
os The package provides three ways to open files, suitable for different scenarios:
| function | Mode | Description |
|---|---|---|
os.Open(name) |
read-only | The simplest way, open for read-only |
os.Create(name) |
Read/write + create/truncate | Create a new file or clear an existing file |
os.OpenFile(name, flag, perm) |
Customization | Can specify read/write, append, create, and other flags |
Example
package
main
import
(
"fmt"
"os"
)
func
main
()
{
// Method 1: open read-only
file
,
err
:=
os
.
Open
(
"example.txt"
)
if
err
!=
nil
{
fmt
.
Println
(
"Open failed:"
,
err
)
return
}
defer
file
.
Close
()
fmt
.
Println
(
"File opened successfully"
)
// Method 2: OpenFile custom mode
// os.O_WRONLY write-only
// os.O_CREATE create if it does not exist
// os.O_APPEND append mode
// os.O_TRUNC truncate if it exists
f
,
err
:=
os
.
OpenFile
(
"log.txt"
,
os
.
O_WRONLY
|
os
.
O_CREATE
|
os
.
O_APPEND
,
0644
)
if
err
!=
nil
{
fmt
.
Println
(
"Open failed:"
,
err
)
return
}
defer
f
.
Close
()
f
.
WriteString
(
"Append a log line\n"
)
}
OpenFile flag descriptions
| Flag | Description |
|---|---|
os.O_RDONLY |
Read-only (default) |
os.O_WRONLY |
Write only |
os.O_RDWR |
Read/write |
os.O_APPEND |
Append mode, written content is appended to the end of the file |
os.O_CREATE |
Create the file if it does not exist |
os.O_TRUNC |
Truncate the file content when opening |
os.O_EXCL |
Used with CREATE, reports an error if the file already exists |
3. Reading files
Go provides three main ways to read files; choose according to file size and processing needs:
3.1 Read all at once (recommended for small files)
os.ReadFile is the most concise way—automatically open, read, and close the file in one step:
Example
package
main
import
(
"fmt"
"log"
"os"
)
func
main
()
{
// Read the entire file at once (Go 1.16+)
data
,
err
:=
os
.
ReadFile
(
"config.json"
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
fmt
.
Println
(
string
(
data
))
}
3.2 Read line by line (recommended for large files)
For large files, use bufio.Scanner to process line by line, avoiding loading everything into memory at once:
Example
package
main
import
(
"bufio"
"fmt"
"log"
"os"
)
func
main
()
{
file
,
err
:=
os
.
Open
(
"large-file.log"
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
defer
file
.
Close
()
// Scan line by line
scanner
:=
bufio
.
NewScanner
(
file
)
lineNum
:=
0
for
scanner
.
Scan
()
{
lineNum
++
line
:=
scanner
.
Text
()
// Get the current line's content
fmt
.
Printf
(
"Line %d: %s\n"
,
lineNum
,
line
)
}
// Check whether any error occurred during scanning
if
err
:=
scanner
.
Err
();
err
!=
nil
{
log
.
Fatal
(
"Read error:"
,
err
)
}
}
Note:
bufio.ScannerThe default maximum line length is 64KB. If the file has extremely long lines, you need to callScan()before settingscanner.Buffer(make([]byte, 0), maxSize)to increase the buffer.
3.3 Reading with io.ReadAll
When you already have an open io.Reader(such as a network response or an already-open file), you can use io.ReadAll:
Example
package
main
import
(
"fmt"
"io"
"log"
"os"
)
func
main
()
{
file
,
err
:=
os
.
Open
(
"example.txt"
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
defer
file
.
Close
()
// Read all data from the Reader
data
,
err
:=
io
.
ReadAll
(
file
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
fmt
.
Println
(
string
(
data
))
}
4. Writing files
Go provides multiple ways to write, from simple one-time writes to high-performance buffered writes:
4.1 Write all at once
os.WriteFile Write data to the file all at once (overwriting the original content):
Example
package
main
import
(
"log"
"os"
)
func
main
()
{
content
:=
[]
byte
(
"Hello, Go!\nThis is the second line\n"
)
// 0644: owner can read/write, other users can only read
err
:=
os
.
WriteFile
(
"output.txt"
,
content
,
0644
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
log
.
Println
(
"Write successful"
)
}
4.2 Writing with a File object
By writing through a file object, you can write content in multiple chunks:
Example
package
main
import
(
"fmt"
"log"
"os"
)
func
main
()
{
file
,
err
:=
os
.
Create
(
"output.txt"
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
defer
file
.
Close
()
// Method 1: write a string
file
.
WriteString
(
"Write a string directly\n"
)
// Method 2: write a byte slice
data
:=
[]
byte
(
"Write a byte slice\n"
)
file
.
Write
(
data
)
// Method 3: formatted write
fmt
.
Fprintf
(
file
,
"Formatted write: %d + %d = %d\n"
,
3
,
4
,
7
)
}
4.3 Buffered writing (recommended for large amounts of data)
bufio.Writer writes data to an in-memory buffer first, then flushes to disk in batches once enough has accumulated, significantly reducing I/O operations. Be sure to call before finishing Flush():
Example
package
main
import
(
"bufio"
"log"
"os"
)
func
main
()
{
file
,
err
:=
os
.
Create
(
"buffered-output.txt"
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
defer
file
.
Close
()
// Create a buffered writer
writer
:=
bufio
.
NewWriter
(
file
)
// Write multiple lines (first into the buffer, not immediately to disk)
for
i
:=
0
;
i
<
1000
;
i
++
{
writer
.
WriteString
(
"This is line "
itoa
(
i
)
" line\n"
)
}
// Flush writes the remaining buffered data to the file
if
err
:=
writer
.
Flush
();
err
!=
nil
{
log
.
Fatal
(
"Failed to flush buffer:"
,
err
)
}
log
.
Println
(
"Buffered write complete"
)
}
// Simple helper function to convert int to string
func
itoa
(
n
int
)
string
{
return
fmt
.
Sprintf
(
"%d"
,
n
)
}
5. Appending to files
Use os.O_APPEND flag appends content at the end of the file without overwriting existing data:
Example
package
main
import
(
"log"
"os"
"time"
)
func
main
()
{
// O_APPEND: append mode
// O_CREATE: create if it does not exist
// O_WRONLY: write-only
file
,
err
:=
os
.
OpenFile
(
"app.log"
,
os
.
O_APPEND
|
os
.
O_CREATE
|
os
.
O_WRONLY
,
0644
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
defer
file
.
Close
()
// Each run appends, never overwrites
timestamp
:=
time
.
Now
()
.
Format
(
"2006-01-02 15:04:05"
)
file
.
WriteString
(
"["
timestamp
"] Application started\n"
)
}
Comparison:
os.Createclears existing content;os.OpenFiletogether withO_APPENDappends content. In logging scenarios, be sure to use append mode.
6. Deleting and renaming files
Example
package
main
import
(
"log"
"os"
)
func
main
()
{
// Rename / move a file
err
:=
os
.
Rename
(
"old.txt"
,
"new.txt"
)
if
err
!=
nil
{
log
.
Fatal
(
"Rename failed:"
,
err
)
}
log
.
Println
(
"Rename successful"
)
// Delete a file
err
=
os
.
Remove
(
"temp.txt"
)
if
err
!=
nil
{
log
.
Fatal
(
"Delete failed:"
,
err
)
}
log
.
Println
(
"Deletion succeeded"
)
}
7. File information and checks
7.1 Getting file information
Example
package
main
import
(
"fmt"
"log"
"os"
)
func
main
()
{
info
,
err
:=
os
.
Stat
(
"test.txt"
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
fmt
.
Println
(
"Filename: "
,
info
.
Name
())
fmt
.
Println
(
"Size: "
,
info
.
Size
(),
"bytes"
)
fmt
.
Println
(
"Permissions: "
,
info
.
Mode
())
fmt
.
Println
(
"Modified: "
,
info
.
ModTime
())
fmt
.
Println
(
"Is directory: "
,
info
.
IsDir
())
}
7.2 Checking whether a file exists
Go has no dedicated "file exists" function; you determine this through os.Stat + os.IsNotExist check:
Example
package
main
import
(
"fmt"
"os"
)
// fileExists checks whether a file exists
func
fileExists
(
path
string
)
bool
{
_
,
err
:=
os
.
Stat
(
path
)
return
!
os
.
IsNotExist
(
err
)
}
func
main
()
{
if
fileExists
(
"test.txt"
)
{
fmt
.
Println
(
"File exists"
)
}
else
{
fmt
.
Println
(
"File does not exist"
)
}
}
8. Directory operations
Example
package
main
import
(
"fmt"
"log"
"os"
)
func
main
()
{
// Create a single directory
err
:=
os
.
Mkdir
(
"newdir"
,
0755
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
// Recursively create multiple levels of directories (parent directories are created automatically if missing)
err
=
os
.
MkdirAll
(
"path/to/deep/dir"
,
0755
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
// Read directory contents
entries
,
err
:=
os
.
ReadDir
(
"."
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
for
_
,
entry
:=
range
entries
{
mark
:=
"📄"
if
entry
.
IsDir
()
{
mark
=
"📁"
}
fmt
.
Printf
(
"%s %s\n"
,
mark
,
entry
.
Name
())
}
// Remove an empty directory
os
.
Remove
(
"newdir"
)
// Recursively remove a directory and all its contents (⚠ use with caution)
os
.
RemoveAll
(
"path"
)
}
9. Advanced operations
9.1 File copying
Use io.Copy Efficiently copy data between two files:
Example
package
main
import
(
"io"
"log"
"os"
)
// copyFile a general function for copying files
func
copyFile
(
src
,
dst
string
)
(
int64
,
error
)
{
srcFile
,
err
:=
os
.
Open
(
src
)
if
err
!=
nil
{
return
0
,
err
}
defer
srcFile
.
Close
()
dstFile
,
err
:=
os
.
Create
(
dst
)
if
err
!=
nil
{
return
0
,
err
}
defer
dstFile
.
Close
()
// io.Copy automatically manages the buffer for efficient copying
return
io
.
Copy
(
dstFile
,
srcFile
)
}
func
main
()
{
n
,
err
:=
copyFile
(
"source.txt"
,
"destination.txt"
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
log
.
Printf
(
"Copy complete, %d bytes in total"
,
n
)
}
9.2 Temporary files and directories
Example
package
main
import
(
"fmt"
"log"
"os"
)
func
main
()
{
// Create a temporary file (automatically named with the prefix "app-")
tmpFile
,
err
:=
os
.
CreateTemp
(
""
,
"app-*.txt"
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
defer
os
.
Remove
(
tmpFile
.
Name
())
// Clean up after use
fmt
.
Println
(
"Temporary file:"
,
tmpFile
.
Name
())
// Create temporary directory
tmpDir
,
err
:=
os
.
MkdirTemp
(
""
,
"app-*"
)
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
defer
os
.
RemoveAll
(
tmpDir
)
// Clean up after use
fmt
.
Println
(
"Temporary directory:"
,
tmpDir
)
}
9.3 Recursively traversing directories
filepath.Walk You can recursively traverse all files and subdirectories in a directory tree:
Example
package
main
import
(
"fmt"
"log"
"os"
"path/filepath"
)
func
main
()
{
root
:=
"."
// Start traversing from the current directory
err
:=
filepath
.
Walk
(
root
,
func
(
path
string
,
info
os.FileInfo
,
err error
)
error
{
if
err
!=
nil
{
return
err
// When an error occurs, you can choose to skip or return
}
// Print the path and size
size
:=
""
if
!
info
.
IsDir
()
{
size
=
fmt
.
Sprintf
(
" (%d bytes)"
,
info
.
Size
())
}
fmt
.
Println
(
path
size
)
return
nil
})
if
err
!=
nil
{
log
.
Fatal
(
err
)
}
}
9.4 Cross-platform path concatenation
Never use string concatenation for paths (such as dir + "/" + file), and use filepath.Join to ensure cross-platform compatibility:
// 错误:Windows 上路径分隔符是 \
path := "dir" + "/" + "file.txt"
// Correct: automatically adapt to the current operating system
path := filepath.Join("dir", "file.txt")
Quick reference by scenario
| Scenario | Recommended approach | Key code |
|---|---|---|
| Read a small file | os.ReadFile |
data, err := os.ReadFile("file.txt") |
| Reading a large file line by line | bufio.Scanner |
scanner := bufio.NewScanner(file) |
| Write a small file | os.WriteFile |
os.WriteFile("f.txt", data, 0644) |
| Write large amounts of data | bufio.Writer |
writer := bufio.NewWriter(file) |
| Append logs | os.OpenFile + O_APPEND |
os.OpenFile("log", os.O_APPEND\|os.O_WRONLY, 0644) |
| Copy files | io.Copy |
io.Copy(dst, src) |
| Traverse the directory | filepath.Walk |
filepath.Walk(".", callback) |
| Path joining | filepath.Join |
filepath.Join("dir", "file.txt") |
| Checks whether the file exists | os.Stat + os.IsNotExist |
_, err := os.Stat(path) |
| Create temporary file | os.CreateTemp |
os.CreateTemp("", "prefix-*.txt") |
File permission notes:
0644means the owner can read and write (6=4+2), while group and other users can only read (4). Directories usually use0755(with the execute permission added; otherwise you cannot enter the directory).