SoFunction
Updated on 2025-03-05

How to read txt documents in Go language

Reading files is one of the most common operations in all programming languages. In this tutorial we will learn how to use Go to read txt documents.

  1. Each line of the document content is a file name information, containing spaces to distinguish different items;
  2. The return is[]bytesSlice type, usestring()Convert tostringType and use()Split into slices by row;
  3. Split the file name information of each line into slices according to spaces.var dataNameSlice [][]string
  4. The file name information of each line is processed into a string string and stored invar dataName []string, use it here()Methods Underline the first 3 information;
package main
 
import (
	"fmt"
	"io/ioutil"
	"strings"
	"os"
)
func main() {
	fileName := ""  // txt file path	data, err_read := (fileName)   // Read the file	if err_read != nil {
		("File reading failed!")
	}
	dataLine := (string(data), "\n") // Slice the file contents as strings by line	var dataNameSlice [][]string                  // Slice used to store contents per line	var dataName []string                         // Organize each line into a string	for i, line := range(dataLine) {
		dataNameSlice = append(dataNameSlice, (line, " "))       // Each line is divided into slices by spaces		dataName = append(dataName, (dataNameSlice[i][:3], "_"))  // The first 3 items of each line's content slice are used to connect to string		dataName[i] = dataName[i] + ".md"
		// (dataName[i])
	for i, dataNameString := range(dataName) {
		if _, err := (dataNameString); (err) { // Determine whether the file exists			(dataNameString)
		} else {
			("%d. [%s] File already exist!\n", i, dataNameString)
		}
}

Additional: golang reads files by line

file, err := ("")
    if err != nil {
        (err)
    }
    defer ()
    scanner := (file)
    for () {
            lineText := ()
 
        }

The entire read

b, err := ("") // just pass the file name
        (err)

str := string(b) // convert content to a 'string'

(str) // print the content as a 'string'

This is the end of this article about reading txt documents in Go. For more relevant content on reading txt documents in Go, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!