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.
- Each line of the document content is a file name information, containing spaces to distinguish different items;
-
The return is
[]bytes
Slice type, usestring()
Convert tostring
Type and use()
Split into slices by row; - Split the file name information of each line into slices according to spaces.
var dataNameSlice [][]string
; - The file name information of each line is processed into a string string and stored in
var 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!