Golang Read File line by line

本文介绍了Golang如何逐行读取文件,作为初学者了解Go语言文件操作的基础教程。

学习什么语言都得从读文件开始,好像记得一个大神说过计算机编程就是"打开文件,操作,关闭文件"。初学Golang就记一下go语言的文件操作

Read File

func main(){ rw,err := os.Open("") if err != nil { panic(err) } defer rw.Close() rb := bufio.NewReader(rw) for { line, _, err := rb.ReadLine() if err == io.EOF { break } //do something fmt.Println(string(line)) } }
func main(){ rw,err := os.Open("") if err != nil { panic(err) } defer rw.Close() sb := bufio.NewScanner(rw) for sb.Scan() { //do something fmt.Println(sb.Text()) } if err := sb.Err(); err !=nil { panic(err) } }
Write File
func main(){ fw,err := os.OpenFile("",os.O_WRONLY|os.O_CREATE|os.O_APPEND,0644) if err != nil { panic(err) } defer fw.Close() wb := bufio.NewWriter(fw) wb.WriteString("hello world\n") wb.Flush() }
Read Dir
func main(){ fw,err := os.OpenFile("",os.O_WRONLY|os.O_CREATE|os.O_APPEND,0644) if err != nil { panic(err) } defer fw.Close() fileinfos, err := fw.Readdir(0) if err != nil { panic(err) } for _, fileinfo := range fileinfos { //do something fmt.Println(fileinfo.Name(), fileinfo.Size()) } }

Go语言本身并不直接支持将Word文档转换成PDF,因为这涉及到复杂的文件格式处理和转换功能,而Go的标准库并没有提供这样的工具。不过,你可以通过引入第三方库来实现这个需求,比如`gopdf`(一个用于生成PDF的库),配合其他专门用于读取Word文档的库,如`github.com/360EntSecGroup-Skylar/excelize/v2` 或 `github.com/OfficeDev/PnP-PowerShell/Commands/Documents`(PowerShell模块)。 以下是一个基本步骤: 1. 安装必要的库: - `gopdf`: 使用`go get github.com/gopdf/gopdf` - Word到XML转换(例如excelize): 如果需要,可以安装`github.com/360EntSecGroup-Skylar/excelize/v2` 2. 使用Excelize或其他库读取Word内容并将其存储为中间格式(如XML)。 3. 使用gopdf创建一个新的PDF文件,并将读取的内容添加到PDF中。 4. 导出PDF文件。 示例代码可能会有所不同,具体取决于你选择的具体库,但是大体上会涉及以下部分: ```go package main import ( "github.com/360EntSecGroup-Skylar/excelize/v2" "github.com/gopdf/gopdf" ) func main() { ex := excelize.NewFile() if err := ex.Read("input.docx"); err != nil { // 替换为实际Word文件路径 // 处理错误... } // 获取Word内容并转换为适合PDF的形式 content := convertToPDFFormat(ex) // 自定义函数 // 创建PDF pdf := gopdf.New() pdf.AddPage() pdf.SetFont("Arial", "B", 16) pdf.Cell(0, 10, "Content from Word") // 将内容添加到PDF for _, line := range content { pdf.Cell(0, 10, line) } // 输出PDF err = pdf.OutputFileAndClose("output.pdf") // 替换为输出文件路径 // 处理错误... } // convertToPDFFormat 为实际内容转换函数 func convertToPDFFormat(ex *excelize.File) []string { // ... 实现将Excelize结构转化为PDF格式的代码 ... return lines // 返回一个字符串切片,每个元素表示PDF中的行 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值