GO writing and reading files with slices

Michael Ushakov
2 min readNov 11, 2024

--

GFU = go file utils

1. How possibly we should work with files using slices

Solving my programming tasks recently, I was figured out that there **are no methods that allowed to get slice of lines and save processed lines on disk. Of course, I could split a string into slice of strings and use that slice, but I would like to have some package once and use it easily, whenever I need it.

Well, I would like to have the following methods:

  1. ReadAllLines that reads file content and return a tuple []string,error
  2. WriteAllLines to write slice of strings
  3. AppendAllLines to add slice of strings to end of existing file.

2.1 New package that meets all requirements

So after I decided what methods such package should have I wrote gfu (gfu is stands for Go File Utils) package and would like to share them with, see github repo:

2.1 ReadAllText method

This method does the following:
1 Returns tuple ([]string, error) of result with auto-detect line ending (CR, LF or CRLF);
2 Removes line ending symbols from slice items
3 Removes empty lines if omitEmpty argument is set to true

Example:

lines, err := gfu.ReadAllLines("myFile.txt", true)

2.2 WriteAllText method

This method does the following:

  1. Inserts the line separator symbol defined in the 3rd argument of WriteAllLines func
  2. Truncates a file if it exists, if not, a file will be created

Example:

lines := []string{
"{",
" \"id\": 1,",
" \"name\": \"Michael Ushakov\"",
"}",
}
file := "write_all_lines_test.txt"
err := gfu.WriteAllLines(file, lines, "\n")

2.3 AppendAllText method

WriteAllLines overwrites file content, but what should we do if we need to add some lines portion to an existing file? We should use the AppendAllLines function that, by signature, is identical to WriteAllLines:

lines := []string{
"{",
" \"id\": 1,",
" \"name\": \"Michael Ushakov\"",
"}",
}
file := "append_all_lines_test.txt"
err := gfu.WriteAllLines(file, lines, "\n")
additionalLines := []string{
"{",
" \"id\": 2,",
" \"name\": \"Alex Petrov\"",
"}",
}
err := gfu.AppendAllLines(file, lines, "\n")

3. Conclusion

All these functions are quite convenient and combined in a small package, also tests were written on all these functions, so we could consider them as reliable. And I go further on my software development journey. don’t forget to give us a star if you find this package helpful.

--

--

Michael Ushakov
Michael Ushakov

Written by Michael Ushakov

I am a scientist (physicist), an engineer (hardware & software) and the CEO of Wissance (wissance.com)