Home >Backend Development >Golang >How Can I Read and Write Text Files as String Arrays in Go?
Reading and Writing Text Files as String Arrays in Go
The ability to handle text files is a common requirement in programming, including reading and writing to string arrays. In Go, a solution exists to address this need.
Reading Text Files
As of Go 1.1, the bufio.Scanner API provides an efficient way to read lines from a file into a string slice. Here's an example:
import ( "bufio" "fmt" "os" ) func readLines(path string) ([]string, error) { file, err := os.Open(path) if err != nil { return nil, err } defer file.Close() var lines []string scanner := bufio.NewScanner(file) for scanner.Scan() { lines = append(lines, scanner.Text()) } return lines, scanner.Err() }
This function reads a whole file into memory and returns a slice of its lines.
Writing Text Files
To write a string slice to a text file, you can use the bufio.Writer type:
import ( "bufio" "fmt" "os" ) func writeLines(lines []string, path string) error { file, err := os.Create(path) if err != nil { return err } defer file.Close() w := bufio.NewWriter(file) for _, line := range lines { fmt.Fprintln(w, line) } return w.Flush() }
This function creates a file, writes the lines to it, and flushes the buffer to ensure the data is written to disk.
Example Usage
Here's an example of how to use these functions:
lines, err := readLines("foo.in.txt") if err != nil { log.Fatalf("readLines: %s", err) } // Process the lines... if err := writeLines(lines, "foo.out.txt"); err != nil { log.Fatalf("writeLines: %s", err) }
This code reads lines from the "foo.in.txt" file, processes them, and writes them to the "foo.out.txt" file.
The above is the detailed content of How Can I Read and Write Text Files as String Arrays in Go?. For more information, please follow other related articles on the PHP Chinese website!