Home >Backend Development >Golang >GO writing and reading files with 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:
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:
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)
This method does the following:
Example:
lines := []string{ "{", " \"id\": 1,", " \"name\": \"Michael Ushakov\"", "}", } file := "write_all_lines_test.txt" err := gfu.WriteAllLines(file, lines, "\n")
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")
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.
The above is the detailed content of GO writing and reading files with slices. For more information, please follow other related articles on the PHP Chinese website!