In recent years, Golang has been favored by developers as an efficient and concise programming language. Its powerful concurrency capabilities and easy-to-learn characteristics make it one of the first choices of many developers. In daily development, reading, modifying and saving files are often involved. This article will introduce how to use Golang to write a file modification program by reading the file content, modifying it and saving the new file.
Before writing the file modification program, you first need to import the standard library that handles file operations in Golang:
package main import ( "fmt" "io/ioutil" "os" )
Next, we define a function to read the file content and perform corresponding modification operations. In this example, we will read a text file, convert the uppercase characters in it to lowercase characters, and save it as a new file.
func modifyFile(inputFile, outputFile string) error { // 读取原文件内容 data, err := ioutil.ReadFile(inputFile) if err != nil { return err } // 将大写字母转换为小写字母 for i, b := range data { if 'A' <= b && b <= 'Z' { data[i] += 'a' - 'A' } } // 将修改后的内容写入新文件 err = ioutil.WriteFile(outputFile, data, 0644) if err != nil { return err } return nil }
Finally, we write the main function, call the file modification function defined above, and pass in the paths of the input file and output file:
func main() { inputFile := "input.txt" outputFile := "output.txt" err := modifyFile(inputFile, outputFile) if err != nil { fmt.Println("文件修改失败:", err) return } fmt.Println("文件修改成功!") }
package main import ( "fmt" "io/ioutil" ) func modifyFile(inputFile, outputFile string) error { data, err := ioutil.ReadFile(inputFile) if err != nil { return err } for i, b := range data { if 'A' <= b && b <= 'Z' { data[i] += 'a' - 'A' } } err = ioutil.WriteFile(outputFile, data, 0644) if err != nil { return err } return nil } func main() { inputFile := "input.txt" outputFile := "output.txt" err := modifyFile(inputFile, outputFile) if err != nil { fmt.Println("文件修改失败:", err) return } fmt.Println("文件修改成功!") }
With the above code, we can implement a simple file modification program to convert uppercase letters in the file to lowercase letters and save it as a new file. This example is just a simple demonstration. In actual applications, more complex file content modification operations can be performed according to requirements. I hope this article will be helpful to you and allow you to better master Golang programming.
The above is the detailed content of File editing tool written in Go language. For more information, please follow other related articles on the PHP Chinese website!