TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang Get Lines in File (String Slice)

Get the lines in a file and store them in a string slice. Use the bufio and os imports.
Get lines, file. For file processing, we often need to get each line in a file. We can store the lines in a string slice, or process each one as we encounter it.
In Golang, the Scanner type (returned by bufio.NewScanner) is helpful here. We can use append() to build up our string slice of file lines. The code can be placed in a separate method.
An example. To begin, please notice how we have imported the "bufio" and "os" packages. These are used in LinesInFile, our most important method in the example.

LinesInFile: We open a file, create a NewScanner with bufio, and call Scan in a loop. The Text func returns each line.

Text: This method returns the line stripped of whitespace on the start and end. So we do not need to deal with newlines ourselves.

Golang program that gets lines in file package main import ( "bufio" "fmt" "os" ) func LinesInFile(fileName string) []string { f, _ := os.Open(fileName) // Create new Scanner. scanner := bufio.NewScanner(f) result := []string{} // Use Scan. for scanner.Scan() { line := scanner.Text() // Append line to result. result = append(result, line) } return result } func main() { // Loop over lines in file. for index, line := range LinesInFile(`C:\programs\file.txt`) { fmt.Printf("Index = %v, line = %v\n", index , line) } // Get count of lines. lines := LinesInFile(`C:\programs\file.txt`) fmt.Println(len(lines)) } Output Index = 0, line = Thank you Index = 1, line = Friend 2
For-range loop. Look carefully at the for-loop in the main method. We receive 2 values for each iteration—the index and the string itself. These can be used in the loop body.
Note, loop. The LinesInFile func is invoked only once for the entire loop. So the file is only opened once. We do not need to worry about excess IO or allocations.

Tip: The file contains the lines "Thank you" and then "Friend." So it is a friendly file at least.

A review. The LinesInFile method is useful for iterating over the lines in a text file in Golang in an efficient way. It handles common forms of newlines well.File
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf