Reading Text Files

I read a lot of text, and other, filed. Today, I want to tackle a common function, so to speak. How to read a text file.


First things first, I need a text file to read.

Screen Shot 2021-03-29 at 8.55.31 AM

I'll name this something clever: text.txt. Next, I need to import a package called bufio which allows me to read buffered streams. I also need the os (operating system) package which allows me to work with files in the operating system. I'll want to print what I read so my import statement looks like:

Screen Shot 2021-03-29 at 8.59.18 AM

Before I can print the contents of the file, I have to open it. In GO, I have to use the Open function in os. This returns two values, a handle to the file, and an error code. If I can't open the file I should log a message. I guess, I should include log in the import statement (I learned about this in a prior post.) This is how I will open the file:



Screen Shot 2021-03-29 at 9.18.48 AM

I've created a function that takes the name of a file to open and returns a file handle (pointer to a file. The return type (*os.File) is the file pointer, which is defined in the os package, so we need to qualify the File type by the package name. If there is no error opening the file, the Open call returns nil.

The next thing I need to do is actually read the file using the returned file handle. I'll create a function to do that.

Screen Shot 2021-03-29 at 9.22.40 AM


This function takes a file handle as a parameter and uses the bufio package to create a new scanner. As its name implies, a scanner lets me scan through the contents of a buffer. In this case, the buffer is attached to the opened file. The next thing I do in this function is use a for loop to read each line in the buffer using the scanner. The Scan function does this. Each time through the loop, I just print the contents of what is being scanned by calling the Text function of the scanner. Text, returns the line the scanner points to. Finally, I check to see if scanner has an error moving through the buffer, I log an error.

The last thing I need to do with a file is close it. It's time for another function.


Screen Shot 2021-03-29 at 9.30.55 AM

This should be straight-forward. I pass in the file handle, then call Close on it and check for an error return.

All, I need now is a main.

Screen Shot 2021-03-29 at 9.32.14 AM


I've called my test program read.go. Now, let's run it.


Screen Shot 2021-03-29 at 9.33.35 AM


It works!

Here's the complete program:


Screen Shot 2021-03-29 at 9.36.30 AM


That's enough for now.


This site does not track your information.