How do you read and write files in Go?
Aug 01, 2025 am 06:56 AMUse os.ReadFile() for reading small files entirely into memory as a byte slice, converting to string with string(content). 2. For large files or line-by-line reading, use bufio.Scanner with os.Open() and defer file.Close() to stream efficiently. 3. Write files using os.WriteFile() with a byte slice and permission setting like 0644, which overwrites existing files. 4. To append to a file, use os.OpenFile() with os.O_APPEND|os.O_CREATE|os.O_WRONLY flags and WriteString(). 5. For JSON data, marshal structs to JSON bytes with json.Marshal() and write using os.WriteFile(), or read with os.ReadFile() and unmarshal with json.Unmarshal(). 6. Always handle errors and use defer to close files when opened manually. 7. Prefer os.ReadFile and os.WriteFile for simplicity with small files, and bufio for streaming or large data to optimize performance. Go provides both high-level convenience and low-level control for file operations, making it efficient and safe when best practices are followed.
Reading and writing files in Go is straightforward thanks to the os
and io/ioutil
(now largely replaced by os
and io
packages in modern Go) packages. Here's how you can do it effectively for common use cases.

1. Reading a File
The most common way to read a file is using os.ReadFile()
(introduced in Go 1.16), which reads the entire file into memory as a byte slice.
package main import ( "fmt" "log" "os" ) func main() { content, err := os.ReadFile("example.txt") if err != nil { log.Fatal(err) } fmt.Println(string(content)) }
- This is ideal for small files.
- Returns
[]byte
, so usestring(content)
to convert to string. - Handles opening and closing the file automatically.
For larger files, or when you want to read line by line (e.g., to save memory), use bufio.Scanner
:

file, err := os.Open("largefile.txt") if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { fmt.Println(scanner.Text()) } if err := scanner.Err(); err != nil { log.Fatal(err) }
This method streams the file, processing one line at a time—great for logs or big data.
2. Writing to a File
To write a string or byte slice to a file, use os.WriteFile()
:

data := []byte("Hello, World!\n") err := os.WriteFile("output.txt", data, 0644) if err != nil { log.Fatal(err) }
Or, if you're writing a string:
err := os.WriteFile("output.txt", []byte("Hello, Go!"), 0644)
- The third argument is the file permission (0644 means owner can read/write, others can read).
- This overwrites the file if it exists.
To append to a file instead:
file, err := os.OpenFile("output.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { log.Fatal(err) } defer file.Close() if _, err := file.WriteString("New line\n"); err != nil { log.Fatal(err) }
This opens the file in append mode and creates it if it doesn’t exist.
3. Working with Structured Data (e.g., JSON)
Go makes it easy to read and write structured data like JSON:
type Person struct { Name string `json:"name"` Age int `json:"age"` } // Writing JSON to file person := Person{Name: "Alice", Age: 30} data, _ := json.Marshal(person) os.WriteFile("person.json", data, 0644) // Reading JSON from file content, _ := os.ReadFile("person.json") var p Person json.Unmarshal(content, &p) fmt.Printf("% v\n", p)
Don’t forget to handle errors in production code.
Key Tips
- Use
defer file.Close()
whenever you manually open a file. - Prefer
os.ReadFile
andos.WriteFile
for simple, small-file operations. - Use
bufio.Scanner
orbufio.Writer
for better performance with large files or streaming. - Always handle errors—file operations are prone to failures (permissions, paths, disk space).
Basically, Go gives you both simple high-level functions and fine-grained control when you need it. For most cases, os.ReadFile
and os.WriteFile
are all you need.
The above is the detailed content of How do you read and write files in Go?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go's switch statement will not be executed throughout the process by default and will automatically exit after matching the first condition. 1. Switch starts with a keyword and can carry one or no value; 2. Case matches from top to bottom in order, only the first match is run; 3. Multiple conditions can be listed by commas to match the same case; 4. There is no need to manually add break, but can be forced through; 5.default is used for unmatched cases, usually placed at the end.

In Go, to break out of nested loops, you should use labeled break statements or return through functions; 1. Use labeled break: Place the tag before the outer loop, such as OuterLoop:for{...}, use breakOuterLoop in the inner loop to directly exit the outer loop; 2. Put the nested loop into the function, and return in advance when the conditions are met, thereby terminating all loops; 3. Avoid using flag variables or goto, the former is lengthy and easy to make mistakes, and the latter is not recommended; the correct way is that the tag must be before the loop rather than after it, which is the idiomatic way to break out of multi-layer loops in Go.

Usecontexttopropagatecancellationanddeadlinesacrossgoroutines,enablingcooperativecancellationinHTTPservers,backgroundtasks,andchainedcalls.2.Withcontext.WithCancel(),createacancellablecontextandcallcancel()tosignaltermination,alwaysdeferringcancel()t

Use a dedicated and reasonably configured HTTP client to set timeout and connection pools to improve performance and resource utilization; 2. Implement a retry mechanism with exponential backoff and jitter, only retry for 5xx, network errors and 429 status codes, and comply with Retry-After headers; 3. Use caches for static data such as user information (such as sync.Map or Redis), set reasonable TTL to avoid repeated requests; 4. Use semaphore or rate.Limiter to limit concurrency and request rates to prevent current limit or blocking; 5. Encapsulate the API as an interface to facilitate testing, mocking, and adding logs, tracking and other middleware; 6. Monitor request duration, error rate, status code and retry times through structured logs and indicators, combined with Op

To correctly copy slices in Go, you must create a new underlying array instead of directly assigning values; 1. Use make and copy functions: dst:=make([]T,len(src));copy(dst,src); 2. Use append and nil slices: dst:=append([]T(nil),src...); both methods can realize element-level copying, avoid sharing the underlying array, and ensure that modifications do not affect each other. Direct assignment of dst=src will cause both to refer to the same array and are not real copying.

InitializeaGomodulewithgomodinit,2.InstallgqlgenCLI,3.Defineaschemainschema.graphqls,4.Rungqlgeninittogeneratemodelsandresolvers,5.Implementresolverfunctionsforqueriesandmutations,6.SetupanHTTPserverusingthegeneratedschema,and7.RuntheservertoaccessGr

Go uses time.Time structure to process dates and times, 1. Format and parse the reference time "2006-01-0215:04:05" corresponding to "MonJan215:04:05MST2006", 2. Use time.Date(year, month, day, hour, min, sec, nsec, loc) to create the date and specify the time zone such as time.UTC, 3. Time zone processing uses time.LoadLocation to load the position and use time.ParseInLocation to parse the time with time zone, 4. Time operation uses Add, AddDate and Sub methods to add and subtract and calculate the interval.

Use the template.ParseFS and embed package to compile HTML templates into binary files. 1. Import the embed package and embed the template file into the embed.FS variable with //go:embedtemplates/.html; 2. Call template.Must(template.ParseFS(templateFS,"templates/.html")))) to parse all matching template files; 3. Render the specified in the HTTP processor through tmpl.ExecuteTemplate(w,"home.html", nil)
