Codecademy Logo

File Handling and I/O Operations in Go

Reading Files in Go

Read the contents of a file in Go using os.ReadFile(name) from the os package, which returns the file’s contents.

Typecast the returned content to a string for readability.

content, err := os.ReadFile("book_data.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(content))

Creating Files in Go

To create a new file or truncate an existing one in Go, use os.Create(name) from the os package.

file, err := os.Create("users/user_one.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()

Changing Directories in Go

Use os.Chdir(name) from Go’s os package to change the application’s working directory.

err := os.Chdir("/logs/user_logs/")
if err != nil {
log.Fatal(err)
}

File Closing in Go

In Go, use File.Close() from the os package to close files. Typically, defer is used with File.Close() to ensure the file is closed automatically after operations are complete.

file, err := os.Open("file_opened.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()

os Package in Go

The os package in Go allows for interaction with the operating system. It supports operations on files and directories, as well as managing environment variables and processes.

File Handling

File handling refers to the process of managing data stored in a computer’s files. This includes reading from files, writing to files, creating new files, and deleting existing files.

Creating Directories in Go

Create directories in Go using os.Mkdir(name, filePerm). This method is useful for organizing files, such as setting up user directories in cloud storage or organizing log files.

The filePerm parameter sets the permissions for who can read and write to the new directory.

err := os.Mkdir("logs", 0755)
if err != nil {
log.Fatal(err)
}

Writing Files in Go

Write data to files in Go using the File.Write(b) and File.WriteString(s) methods from the os.File type.

file, err := os.Create("Hello World.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
/* File.WriteString() */
numBytes, err := file.WriteString("Hello, World!")
if err != nil {
log.Fatal(err)
}
/* File.Write() */
data := []byte("Hello, World!")
numBytes, err = file.Write(data)
if err != nil {
log.Fatal(err)
}

Learn More on Codecademy