File Operations with the Go Programming Language (Golang)
By: Aman Khanakia
Tags: Golang Tools, Golang Development, Golang Tutorial, Golang

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.txt have created our named file with a very simple use .

2- File Reading & Opening Operations

In order to understand the essence of the event, I txt will work on the files too, but do not forget that: I could choose a file with an extension txt instead of as png a 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.

: 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.

file, err := os.OpenFile("deneme.txt", os.O_RDWR|os.O_CREATE, 0755)

if err != nil {

panic(err)

} // Blok sonunda dosyayı kapat

defer file.Close()

deneme.txt We read our file with a small piece of code that we use in our main program . As you notice when selecting this file , it is indicated first dosya ismi , then işlem tipi (flag) , then dosya izni . Let's talk quickly about what our transaction types are because this part is very important;

O_RDONLY : read-only Opens the file for reading only ( ).

: Opens the file for reading only ( ). O_WRONLY : write-only Opens the file for writing ( ) only . (To be used in writing below)

: Opens the file for writing ( ) only . (To be used in writing below) O_RDWR : read-write Opens the file for both reading and writing ( ).

One of these three parameters must be used. However, in addition to the above, there are five other variables that we can preferentially use;

O_APPEND : Adds the data to the end of the file while writing to the file.

: Adds the data to the end of the file while writing to the file. O_CREATE : When opening the file, if there is no file with the specified name, it creates.

: When opening the file, if there is no file with the specified name, it creates. O_EXCL : Used with O_CREATE. A file with the specified name must not exist in order to create a new file.

: Used with O_CREATE. A file with the specified name must not exist in order to create a new file. O_SYNC : Allows the file to be opened for synchronous I / O.

: file to be opened for synchronous I / O. O_TRUNC : If the file already exists and it is a normal file, truncate 0 length file.

Talking about the file permission, as in Linux, O_CREATE if the file does not exist with parameter, you can assign the permission value to the file while creating a new file. Click for detailed information about permissions .

2.3- Printing the File Line by Line

After selecting the file, we may want to select all lines one by one and write on the screen. For this, we can choose a usage like below. Of course, you can play and process each line separately as you move line by line on the file.

file, err := os.OpenFile("deneme.txt", os.O_RDONLY, 0755)

if err != nil {

panic(err)

} // Blok sonunda dosyayı kapat

defer file.Close() // Satır satır oku

scanner := bufio.NewScanner(file)

for scanner.Scan() {

satir := scanner.Text()

fmt.Println(satir)

} if err := scanner.Err(); err != nil {

log.Fatal(err)

}

2.4- Accessing File Meta Information

We can easily access many meta properties such as the name, date and size of a file we choose. For this, you can use the Open() or OpenFile() methods when opening the file, but we Stat() will select our file using the method for the widest meta properties .

file, err := os.Stat("deneme.txt")

if err != nil {

panic(err)

} fmt.Println("Dosya Adı: ", file.Name())

fmt.Println("Dosya Boyutu: ", file.Size())

fmt.Println("Dosya İzni: ", file.Mode())

fmt.Println("Dosya Tarihi: ", file.ModTime())

fmt.Println("Dosya Klasör mü: ", file.IsDir())

fmt.Println("Dosya Kaynağı: ", file.Sys())

If we look at the output of this program;

Dosya Adı: deneme.txt

Dosya Boyutu: 140

Dosya İzni: -rw-rw-rw-

Dosya Tarihi: 2020-09-03 13:53:54.5489958 +0300 +03

Dosya Klasör mü: false

Dosya Kaynağı: &{32 {3989454219 30844384} {3079957368 30844484} {2218824230 30835168} 0 140}

Let’s collect the information we can get in a list;

Name() string // Shows the file name

string // Shows the file name Size() int64 // Shows the file size in bytes

int64 // Shows the file size in bytes Mode() FileMode // Shows the file type

FileMode // Shows the file type ModTime() time.Time // Shows the last edit date of the file

time.Time // Shows the last edit date of the file IsDir() bool // Indicates whether the file is a folder

bool // Indicates whether the file is a folder Sys() interface {} // Shows the file source

3- Writing to File Operations

We can now read our files easily. So how can we add the data we want to these files? The answer to this question is quite simple as you will see in a moment. The only thing you need to be aware of is which modes you will use additionally after opening the file in O_WRONLY mode. If you want, let’s look at these modes and move on to the examples.

O_RDONLY : read-only Opens the file for reading only ( ). (We used it in reading operations above)

: Opens the file for reading only ( ). (We used it in reading operations above) O_WRONLY : write-only Opens the file for writing ( ) only .

: Opens the file for writing ( ) only . O_RDWR : read-write Opens the file for both reading and writing ( ).

One of these two parameters must be used. However, in addition to the above, there are five other variables that we can preferentially use;

O_APPEND : Adds the data to the end of the file while writing to the file.

: Adds the data to the end of the file while writing to the file. O_CREATE : When opening the file, if there is no file with the specified name, it creates.

: When opening the file, if there is no file with the specified name, it creates. O_EXCL : Used with O_CREATE. A file with the specified name must not exist in order to create a new file.

: Used with O_CREATE. A file with the specified name must not exist in order to create a new file. O_SYNC : Allows the file to be opened for synchronous I / O.

: file to be opened for synchronous I / O. O_TRUNC : If the file already exists and it is a normal file, truncate 0 length file.

So let’s do a little example.

file, err := os.OpenFile("deneme.txt", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)

if err != nil {

log.Fatal(err)

} // Fonksiyon sonunda dosyayı kapat

defer file.Close() // Dosyaya yaz

len, err := file.WriteString("Merhaba, bu string dosyanın sonuna eklenecek")

if err != nil {

log.Fatal(err)

} else {

log.Println("Yazılan byte boyutu: " + strconv.Itoa(len))

}

As you can see, it’s that simple to write to the file. If you want to go to the bottom line after the value you have written, "

" add it to the end of your text .

4- Closing Files

After we have finished working on the files, we must finally close it to be able to release the file. We Close() can use the function for this .

file, err := os.Open("deneme.txt")

if err != nil {

log.Fatal(err)

} file.Close()

5- Deleting Files

We can do numerous operations on files. One of the most common of these is the ability to delete files. We will use the Remove() and RemoveAll() functions for file deletion with Go .

Remove() : Deletes the specified file

: Deletes the specified file RemoveAll() : Deletes all files in a directory