File create, read, and write the basic operations in Go. We can create a file using the os.Create() function. First, we must import the os package and then use its method.
How to create a file in Golang
To create a file in Golang, use the os.Create() function. Golang has a built-in os.Create() function that takes the filename as the argument and creates a file with the specified name or an error.
func Create()
func Create(name string) (*File, error)
The Create() function is an inbuilt function that creates or truncates the named file. If the file already exists, it is truncated. If the file does not exist, it will be created with mode 0666 (before umask).
If successful, methods on the returned File can be used for I/O; the associated file descriptor has mode O_RDWR. If there is an error, it will be of type *PathError.
If we rerun the above code, then it truncates the existing file. This function returns a File descriptor.
You can open the file using os.Open() function.
Let’s create an empty file in Go first. For that, import the os module.
// hello.go package main import ( "log" "os" ) func main() { emptyFile, err := os.Create("emptyFile.txt") if err != nil { log.Fatal(err) } log.Println(emptyFile) emptyFile.Close() }
In the above code, we have imported log and os packages.
Then inside the main() function, we used an os.Create() function and pass the filename that we want to create. If the error occurs, it will log, and the program will be stopped; otherwise, it will log the new empty file.
You can find the emptyFile.txt file in the same directory as hello.go.
Conclusion
In Golang, use the os package and use the os.Create() function to create a file. We can open the file using os.Open() function. We are also using defer to close the file access once the function has finished running (which is an elegant way of remembering to close files).
That’s it.
Hi, thank you for the snipped.
Can you create the emptyFile.txt file in a diferent directory as hello.go?
Thank you for your help.