Today a short one again. I have played around with some go again and wanted to write it down. There are multiple options to some of the stuff i did. So this is not a comprehensive guide.
Check if file exists
func fileExists(fileName string) (bool, error) {
info, err := os.Stat(fileName)
if err != nil {
if os.IsNotExist(err) {
return false, nil
} else {
return false, err
}
}
return !info.IsDir(), nil
}
Create a file and write text to it
created, err = os.Create("test.txt")
if err != nil {
log.Fatal(err)
}
//write to text file
//i ignore the number of bytes writen here
_, err = created.WriteString("Hello World")
if err != nil {
log.Fatal(err)
}
//Close the file so it can be used later
created.Close()
Learned a lesson here. In my first version i wrote defer created.close(). But than later ran into problems, when i wanted to read from the file. So you need to close the file if you want to read from it in the same function.
Delete a file
created, err = os.Create("toDelete.txt")
if err != nil {
log.Fatal(err)
}
created.Close()
err := os.Remove("toDelete.txt")
if err != nil {
log.Fatal(e)
}
Read from a text file - 1
anotherFile, err := os.Open("anotherFile.txt")
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(anotherFile)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
Read from a text file - 2
content, err := os.ReadFile(fileName)
if err != nil {
log.Fatal(err)
}
//The content is a []byte because of that: string(...)
fmt.Println(string(content))
}
Not much to adress here. I slowy see the verbosity of go. Haven't made up my mind about the language yet.
Copy or move a file
//copy a file
bytesRead, err := ioutil.ReadFile("fileToCopy.txt")
if err != nil {
log.Fatal(err)
}
ioutil.WriteFile("cptrgt/CopyTarget.txt", bytesRead, os.ModePerm)
//Move a file
err = os.Rename("oldFile.txt", "cptrgt/newFile.txt")
if err != nil {
log.Fatal(err)
}
Don't like how to move a file. Not a catastrophe but also not really intuitive either. Have not tested the copy speeds yet.
Create and recursivly delete a Folder
//create a new Folder
if err := os.Mkdir("cptrgt", os.ModePerm); err != nil {
log.Fatal(err)
}
//delete a folder recursively
err := os.RemoveAll("cptrgt")
if err != nil {
log.Fatal(err)
}
After my last post i was happy a about the syntax but now i stumble more and mor about how verbose it is. Honestly i would say i'm not sold on go for quick commandline tools. I see the great performance and simple deployment, but at the moment i wouldn't trade it for python, java or the powershell. But i will keep learning and maybe i will be convinced.
Top comments (0)