Member-only story

File Operations with the Go Programming Language (Golang)

Luci Bro
6 min readDec 28, 2020

--

With Go file reading, writing, editing and deleting operations, you can easily perform operations on any file. Golang uses different libraries for file operations and manages your files. In this lesson, we will see with examples how to do various file operations with Go (Golang) .

Go is a powerful language and with the motto Everything Is A File, which is the basis of Linux , it can successfully perform operations on any type of file. When you come to this article, you may have only txt and json files in mind, but let’s say that you have to know that you can read, write and edit on any file regardless of its extension. You just choose your file as I will explain below and start the process.

1- File Creation

Let’s also see how we can create a new file with Golang before we see how to read, write, edit and delete files. We use the Create () method for this.

file, err := os.Create("dosya.txt")
if err != nil {
log.Fatal(err)
}
// Fonksiyon sonunda dosyayı kapat
defer file.Close()

We dosya.txthave created our named file with a very simple use .

2- File Reading & Opening Operations

In order to understand the essence of the event, I txtwill work on the files too, but do not forget that: I could choose a file with an extension txtinstead of as pnga file. After all, every object is a file. So now let's first select and read our file. We can use one of its functions in Open()or OpenFile().

2.1- Difference of Open () and OpenFile () Functions

We said that we can use one of these two functions to select and open files. The difference between the two functions is briefly;

  • Open() : Opens files in ReadOnly mode only.
  • OpenFile() : We can select files in multiple modes and perform many operations on the file.

2.2- Selecting the File

We select our file with the following method and specify the processing mode. In addition, if the file does not exist, we can determine the file permission to be given while creating.

--

--

No responses yet

Write a response