{"id":814,"date":"2026-10-08T15:00:00","date_gmt":"2026-10-08T09:30:00","guid":{"rendered":"https:\/\/smitabharat.com\/blog\/go-file-programs\/"},"modified":"2026-11-29T01:29:30","modified_gmt":"2026-11-28T19:59:30","slug":"go-file-programs","status":"publish","type":"post","link":"https:\/\/smitabharat.com\/blog\/go-file-programs\/","title":{"rendered":"Go File Programs with Output: Read, Write, Append and Walk"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Go file programs read, write and manage files on disk, such as saving a report, loading a config or counting lines in a log. In this post, you will write fourteen file programs with their exact output, and every program explains its logic step by step in the code comments. We finish with the file programs interviewers ask most, such as counting words in a file and finding the longest line.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This post starts Level 5 of our Go programs series. It uses error handling from our <a href=\"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/\">Go error handling programs<\/a> and the input tools from our <a href=\"https:\/\/smitabharat.com\/blog\/go-user-input-programs\/\">Go user input programs<\/a>. For the theory, read the <a href=\"https:\/\/smitabharat.com\/blog\/go-file-handling-examples\/\">Go file handling guide<\/a>. All programs were tested on Go 1.27.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What are Go File Programs?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Go file programs use the <code>os<\/code>, <code>bufio<\/code> and <code>io<\/code> packages to create, read, change and delete files. A file is opened, used and then closed, and every step can return an error that you must check.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Think of a file like a notebook in a cupboard. You open the cupboard (open the file), read or write pages, and then put the notebook back and close the door (close the file). If you forget to close it, other people may not be able to use it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why Go File Programs Matter<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Almost every backend program touches files. For example, a service reads a config file at start-up, a job writes a daily CSV report and a tool scans log files for errors. So Go file programs are a practical skill you will use every week.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Configs and data:<\/strong> load settings, templates and seed data.<\/li>\n\n\n<li><strong>Reports:<\/strong> write CSV or text files for other teams.<\/li>\n\n\n<li><strong>Logs:<\/strong> read big log files line by line without loading them into memory.<\/li>\n\n\n<li><strong>Interviews:<\/strong> count lines, words and characters is a classic coding task.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">How Go File Programs Work<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Most file work follows four steps. First, open or create the file and check the error. Next, read or write data. Then close the file, usually with <code>defer<\/code>. Finally, handle any error from the read, write or close.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-diagram-1-1024x640.png\" alt=\"Go file programs diagram showing open, read or write, close and error check steps\" class=\"wp-image-812\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-diagram-1-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-diagram-1-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-diagram-1-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-diagram-1-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-diagram-1-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Open the file and check the error, read or write the data, close it with defer, and handle any error along the way.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The table below lists the file tools in this post.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Task<\/th><th>Function<\/th><th>Good for<\/th><\/tr><\/thead><tbody><tr><td>Write a whole file<\/td><td>os.WriteFile<\/td><td>Small files in one go<\/td><\/tr><tr><td>Read a whole file<\/td><td>os.ReadFile<\/td><td>Small files that fit in memory<\/td><\/tr><tr><td>Open for reading<\/td><td>os.Open<\/td><td>Reading step by step<\/td><\/tr><tr><td>Create or truncate<\/td><td>os.Create<\/td><td>Writing a new file<\/td><\/tr><tr><td>Append<\/td><td>os.OpenFile with O_APPEND<\/td><td>Adding to logs<\/td><\/tr><tr><td>Read line by line<\/td><td>bufio.Scanner<\/td><td>Big files<\/td><\/tr><tr><td>Copy<\/td><td>io.Copy<\/td><td>Any size, low memory<\/td><\/tr><tr><td>File info<\/td><td>os.Stat<\/td><td>Size, time, exists or not<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Basic Go File Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These first Go file programs write and read whole files. Each program works in a temporary folder, so it is safe to run anywhere, including the Go Playground.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 1: Your First File Program<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"           \/\/ fmt prints text on the screen\n    \"os\"            \/\/ os works with files and folders\n    \"path\/filepath\" \/\/ filepath builds file paths\n)\n\nfunc main() {\n    \/\/ Step 1: make a temporary folder so we never touch your real files.\n    \/\/ err is the error value. It is nil (empty) when nothing went wrong.\n    folder, err := os.MkdirTemp(\"\", \"first\")\n    if err != nil {\n        fmt.Println(\"folder error:\", err)\n        return\n    }\n    defer os.RemoveAll(folder) \/\/ defer runs this when main ends, so the folder is deleted\n\n    \/\/ Step 2: create a new, empty file inside the folder.\n    path := filepath.Join(folder, \"hello.txt\")\n    file, err := os.Create(path)\n    if err != nil {\n        fmt.Println(\"create error:\", err)\n        return\n    }\n\n    \/\/ Step 3: write one line, then close the file.\n    file.WriteString(\"Hello, file!\\n\")\n    file.Close()\n\n    \/\/ Step 4: read the file back and print what is inside.\n    data, err := os.ReadFile(path)\n    if err != nil {\n        fmt.Println(\"read error:\", err)\n        return\n    }\n    fmt.Print(\"File says: \", string(data)) \/\/ string() turns bytes into text\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>File says: Hello, file!<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">First, you make a safe temporary folder and create <code>hello.txt<\/code> inside it. Then you write one line and close the file. Finally, <code>os.ReadFile<\/code> reads the bytes back, and <code>string()<\/code> turns them into text you can print.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 2: Write and Read a Whole File<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path\/filepath\"\n)\n\nfunc main() {\n    \/\/ Make a temporary folder so we never touch real files.\n    folder, err := os.MkdirTemp(\"\", \"demo\")\n    if err != nil {\n        fmt.Println(\"mkdir error:\", err)\n        return\n    }\n    defer os.RemoveAll(folder) \/\/ clean up the folder when main ends\n\n    \/\/ filepath.Join builds a correct path on any OS.\n    path := filepath.Join(folder, \"notes.txt\")\n\n    \/\/ Step 1: write the whole file at once.\n    \/\/ []byte(...) turns the text into bytes, which files store.\n    \/\/ 0644 = owner can read and write, others can only read.\n    err = os.WriteFile(path, []byte(\"Learn Go\\nWrite code\\n\"), 0644)\n    if err != nil {\n        fmt.Println(\"write error:\", err)\n        return\n    }\n\n    \/\/ Step 2: read the whole file back into memory.\n    data, err := os.ReadFile(path)\n    if err != nil {\n        fmt.Println(\"read error:\", err)\n        return\n    }\n    fmt.Print(string(data))\n    fmt.Println(\"Bytes:\", len(data)) \/\/ len counts the bytes\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Learn Go\nWrite code\nBytes: 20<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>os.WriteFile<\/code> creates the file if needed and replaces any old content. <code>os.ReadFile<\/code> returns bytes, so we convert them to a string to print. The file has 20 bytes, because each <code>\\n<\/code> new line also counts as one byte.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 3: Append Lines to a Log File<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path\/filepath\"\n)\n\n\/\/ appendLine adds one line to the end of a file.\nfunc appendLine(path, line string) error {\n    \/\/ O_APPEND: always write at the end.\n    \/\/ O_CREATE: create the file if it does not exist.\n    \/\/ O_WRONLY: open for writing only.\n    \/\/ The | sign joins the three options together.\n    file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n    if err != nil {\n        return err\n    }\n    defer file.Close() \/\/ close the file when this function returns\n\n    _, err = file.WriteString(line + \"\\n\")\n    return err\n}\n\nfunc main() {\n    \/\/ The _ ignores the error here to keep the demo short.\n    folder, _ := os.MkdirTemp(\"\", \"logs\")\n    defer os.RemoveAll(folder)\n    path := filepath.Join(folder, \"app.log\")\n\n    \/\/ Each call adds one line without removing old lines.\n    messages := []string{\"server started\", \"user login\", \"server stopped\"}\n    for _, message := range messages {\n        err := appendLine(path, message)\n        if err != nil {\n            fmt.Println(\"error:\", err)\n        }\n    }\n    data, _ := os.ReadFile(path)\n    fmt.Print(string(data))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>server started\nuser login\nserver stopped<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>appendLine<\/code> function opens the file with three flags joined by <code>|<\/code>. Then it writes one line at the end. Without <code>O_APPEND<\/code>, each write would start at the beginning of the file.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 4: Check if a File Exists<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"io\/fs\"\n    \"os\"\n    \"path\/filepath\"\n)\n\n\/\/ exists returns true if the file is there, and false if it is missing.\nfunc exists(path string) bool {\n    \/\/ os.Stat returns file info, or an error if something is wrong.\n    _, err := os.Stat(path)\n\n    \/\/ fs.ErrNotExist means the file is simply missing.\n    if errors.Is(err, fs.ErrNotExist) {\n        return false\n    }\n    return true\n}\n\nfunc main() {\n    folder, _ := os.MkdirTemp(\"\", \"check\")\n    defer os.RemoveAll(folder)\n\n    configPath := filepath.Join(folder, \"config.json\")\n    os.WriteFile(configPath, []byte(\"{}\"), 0644)\n    missingPath := filepath.Join(folder, \"missing.json\")\n\n    fmt.Println(\"config.json:\", exists(configPath))\n    fmt.Println(\"missing.json:\", exists(missingPath))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>config.json: true\nmissing.json: false<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>os.Stat<\/code> asks the system about the file. We check the error with <code>errors.Is<\/code>, as in our error handling post. Other errors, such as &#8220;permission denied&#8221;, mean the file may exist but we cannot see it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Line-by-Line Go File Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Big files can be gigabytes in size. These Go file programs read one line at a time, so memory use stays tiny.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 5: Read a File Line by Line<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"path\/filepath\"\n)\n\nfunc main() {\n    folder, _ := os.MkdirTemp(\"\", \"read\")\n    defer os.RemoveAll(folder)\n    path := filepath.Join(folder, \"cities.txt\")\n    os.WriteFile(path, []byte(\"Pune\\nDelhi\\nGoa\\n\"), 0644)\n\n    file, err := os.Open(path) \/\/ open for reading only\n    if err != nil {\n        fmt.Println(\"open error:\", err)\n        return\n    }\n    defer file.Close()\n\n    \/\/ Scanner reads one line per Scan() call.\n    scanner := bufio.NewScanner(file)\n    lineNumber := 0\n    for scanner.Scan() { \/\/ the loop stops when there are no more lines\n        lineNumber++\n        fmt.Printf(\"%d: %s\\n\", lineNumber, scanner.Text()) \/\/ %d is a number, %s is text\n    }\n\n    \/\/ Always check for a read error after the loop.\n    err = scanner.Err()\n    if err != nil {\n        fmt.Println(\"scan error:\", err)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>1: Pune\n2: Delhi\n3: Goa<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>bufio.NewScanner<\/code> wraps the open file. Each <code>Scan<\/code> call moves to the next line, and <code>scanner.Text()<\/code> gives the line without the new line character. The final <code>scanner.Err()<\/code> check catches problems like a broken disk.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 6: Add Up Numbers Stored in a File<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"path\/filepath\"\n    \"strconv\"\n)\n\nfunc main() {\n    folder, _ := os.MkdirTemp(\"\", \"expenses\")\n    defer os.RemoveAll(folder)\n    path := filepath.Join(folder, \"expenses.txt\")\n    os.WriteFile(path, []byte(\"120\\n45\\nabc\\n300\\n\"), 0644)\n\n    file, err := os.Open(path)\n    if err != nil {\n        fmt.Println(\"open error:\", err)\n        return\n    }\n    defer file.Close()\n\n    total := 0\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        line := scanner.Text()\n\n        \/\/ Step 1: turn the text into a number. Atoi means \"ASCII to integer\".\n        amount, err := strconv.Atoi(line)\n        if err != nil {\n            fmt.Println(\"Skipped, not a number:\", line)\n            continue \/\/ jump to the next line\n        }\n\n        \/\/ Step 2: add the number to the running total.\n        total += amount\n        fmt.Println(\"Added\", amount)\n    }\n    fmt.Println(\"Total spent:\", total)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Added 120\nAdded 45\nSkipped, not a number: abc\nAdded 300\nTotal spent: 465<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The scanner reads one line at a time, just like in Program 5. Then <code>strconv.Atoi<\/code> turns each line into a number. If a line is not a number, <code>continue<\/code> skips it, so one bad line does not stop the whole sum.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 7: Copy a File with io.Copy<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"io\"\n    \"os\"\n    \"path\/filepath\"\n)\n\n\/\/ copyFile copies the source file into the target file and returns the bytes copied.\nfunc copyFile(source, target string) (int64, error) {\n    sourceFile, err := os.Open(source)\n    if err != nil {\n        return 0, err\n    }\n    defer sourceFile.Close()\n\n    targetFile, err := os.Create(target) \/\/ creates or empties the target\n    if err != nil {\n        return 0, err\n    }\n    defer targetFile.Close()\n\n    \/\/ io.Copy moves data in small chunks, so even huge files use little memory.\n    return io.Copy(targetFile, sourceFile)\n}\n\nfunc main() {\n    folder, _ := os.MkdirTemp(\"\", \"copy\")\n    defer os.RemoveAll(folder)\n    source := filepath.Join(folder, \"report.txt\")\n    target := filepath.Join(folder, \"backup.txt\")\n    os.WriteFile(source, []byte(\"Q3 sales: 4.2 lakh\"), 0644)\n\n    copiedBytes, err := copyFile(source, target)\n    fmt.Println(\"copied bytes:\", copiedBytes, \"error:\", err)\n    data, _ := os.ReadFile(target)\n    fmt.Println(string(data))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>copied bytes: 18 error: &lt;nil&gt;\nQ3 sales: 4.2 lakh<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>copyFile<\/code> opens the source for reading and creates the target for writing. Then <code>io.Copy<\/code> moves the bytes from one to the other. The error prints as <code>&lt;nil&gt;<\/code>, which means the copy worked.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 8: File Size and Info<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path\/filepath\"\n)\n\nfunc main() {\n    folder, _ := os.MkdirTemp(\"\", \"info\")\n    defer os.RemoveAll(folder)\n    path := filepath.Join(folder, \"photo.txt\")\n    os.WriteFile(path, []byte(\"1234567890\"), 0644)\n\n    \/\/ os.Stat returns facts about the file, such as its name and size.\n    info, err := os.Stat(path)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(\"Name:\", info.Name())\n    fmt.Println(\"Size:\", info.Size(), \"bytes\")\n    fmt.Println(\"Is folder:\", info.IsDir())\n    fmt.Println(\"Mode:\", info.Mode()) \/\/ the read and write permissions\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Name: photo.txt\nSize: 10 bytes\nIs folder: false\nMode: -rw-r--r--<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>os.Stat<\/code> gives you an <code>info<\/code> value with small methods for each fact. <code>Mode<\/code> shows the permissions we passed as <code>0644<\/code>. The modification time also lives in <code>info.ModTime()<\/code>, but we skip it because it changes every run.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Folder and CSV Go File Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These Go file programs work with folders and spreadsheet-style data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 9: List Files in a Folder<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path\/filepath\"\n)\n\nfunc main() {\n    folder, _ := os.MkdirTemp(\"\", \"list\")\n    defer os.RemoveAll(folder)\n\n    \/\/ Create a few files and one sub-folder.\n    for _, name := range []string{\"b.txt\", \"a.go\", \"c.csv\"} {\n        os.WriteFile(filepath.Join(folder, name), []byte(\"x\"), 0644)\n    }\n    os.Mkdir(filepath.Join(folder, \"images\"), 0755)\n\n    \/\/ os.ReadDir returns entries already sorted by name.\n    entries, err := os.ReadDir(folder)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    for _, entry := range entries {\n        kind := \"file\"\n        if entry.IsDir() {\n            kind = \"folder\"\n        }\n        fmt.Println(entry.Name(), \"-\", kind)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>a.go - file\nb.txt - file\nc.csv - file\nimages - folder<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">First, the program creates three files and one folder. Then <code>os.ReadDir<\/code> returns every entry, sorted by name. For each entry, <code>IsDir<\/code> tells you whether it is a folder or a file.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 10: Write and Read a CSV File<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"encoding\/csv\"\n    \"fmt\"\n    \"os\"\n    \"path\/filepath\"\n)\n\nfunc main() {\n    folder, _ := os.MkdirTemp(\"\", \"csv\")\n    defer os.RemoveAll(folder)\n    path := filepath.Join(folder, \"students.csv\")\n\n    \/\/ Step 1: write the rows. Each row is a list of text cells.\n    file, _ := os.Create(path)\n    writer := csv.NewWriter(file)\n    rows := [][]string{{\"name\", \"marks\"}, {\"Asha\", \"91\"}, {\"Ravi, Jr\", \"78\"}}\n    writer.WriteAll(rows) \/\/ WriteAll also flushes the buffer\n    file.Close()\n\n    \/\/ Step 2: open the file again and read every row.\n    file, _ = os.Open(path)\n    defer file.Close()\n    records, err := csv.NewReader(file).ReadAll()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    \/\/ records[1:] means \"all rows from index 1\", so it skips the header row.\n    for _, record := range records[1:] {\n        fmt.Printf(\"%s scored %s\\n\", record[0], record[1])\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Asha scored 91\nRavi, Jr scored 78<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">&#8220;Ravi, Jr&#8221; has a comma inside, so the CSV writer wraps it in quotes. The reader removes the quotes again. That is why you should never split CSV lines with <code>strings.Split<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 11: Delete a File Safely<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"io\/fs\"\n    \"os\"\n    \"path\/filepath\"\n)\n\nfunc main() {\n    folder, _ := os.MkdirTemp(\"\", \"del\")\n    defer os.RemoveAll(folder)\n    path := filepath.Join(folder, \"temp.txt\")\n    os.WriteFile(path, []byte(\"bye\"), 0644)\n\n    \/\/ The first remove works, so the error is nil.\n    fmt.Println(\"first remove:\", os.Remove(path))\n\n    \/\/ Removing again fails, because the file is already gone.\n    err := os.Remove(path)\n    fmt.Println(\"second remove is not-exist:\", errors.Is(err, fs.ErrNotExist))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>first remove: &lt;nil&gt;\nsecond remove is not-exist: true<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>os.Remove<\/code> deletes the file and returns <code>nil<\/code> on success. The second call fails, because the file is gone. With <code>errors.Is<\/code>, you can tell &#8220;already deleted&#8221; apart from real problems.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Most Asked Interview Go File Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These Go file programs are the ones interviewers ask most often.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 12: Count Lines, Words and Characters<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This is the Go version of the Unix <code>wc<\/code> command.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"path\/filepath\"\n    \"strings\"\n    \"unicode\/utf8\"\n)\n\nfunc main() {\n    folder, _ := os.MkdirTemp(\"\", \"wc\")\n    defer os.RemoveAll(folder)\n    path := filepath.Join(folder, \"story.txt\")\n    os.WriteFile(path, []byte(\"Go is simple\\nGo is fast\\n\\nGo is fun\\n\"), 0644)\n\n    file, _ := os.Open(path)\n    defer file.Close()\n\n    lines := 0\n    words := 0\n    chars := 0\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        line := scanner.Text()\n        lines++                               \/\/ every Scan is one line\n        words += len(strings.Fields(line))    \/\/ Fields splits on spaces\n        chars += utf8.RuneCountInString(line) \/\/ count characters, not bytes\n    }\n    fmt.Println(\"Lines:\", lines, \"Words:\", words, \"Chars:\", chars)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Lines: 4 Words: 9 Chars: 31<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The scanner gives one line at a time, and each line adds one to <code>lines<\/code>. <code>strings.Fields<\/code> splits the line into words, so we add how many it found. The empty third line still counts as a line, but it adds no words.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 13: Find the Longest Line<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"path\/filepath\"\n)\n\nfunc main() {\n    folder, _ := os.MkdirTemp(\"\", \"long\")\n    defer os.RemoveAll(folder)\n    path := filepath.Join(folder, \"log.txt\")\n    os.WriteFile(path, []byte(\"ok\\nerror: disk almost full\\nwarn: slow\\n\"), 0644)\n\n    file, _ := os.Open(path)\n    defer file.Close()\n\n    longest := \"\"      \/\/ the longest line seen so far\n    longestNumber := 0 \/\/ its line number\n    current := 0       \/\/ the line we are reading now\n    scanner := bufio.NewScanner(file)\n    for scanner.Scan() {\n        current++\n        line := scanner.Text()\n        \/\/ Keep the line only if it is longer than the best so far.\n        if len(line) &gt; len(longest) {\n            longest = line\n            longestNumber = current\n        }\n    }\n    \/\/ %q prints the text inside double quotes.\n    fmt.Printf(\"Line %d is longest: %q (%d chars)\\n\", longestNumber, longest, len(longest))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Line 2 is longest: \"error: disk almost full\" (23 chars)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The program remembers the longest line and its number. For each new line, it compares the length with the best so far. If the new line is longer, it becomes the new best.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 14: Word Frequency from a File<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"maps\"\n    \"os\"\n    \"path\/filepath\"\n    \"slices\"\n    \"strings\"\n)\n\nfunc main() {\n    folder, _ := os.MkdirTemp(\"\", \"freq\")\n    defer os.RemoveAll(folder)\n    path := filepath.Join(folder, \"words.txt\")\n    os.WriteFile(path, []byte(\"Go go GO\\nrust Go\\n\"), 0644)\n\n    file, _ := os.Open(path)\n    defer file.Close()\n\n    \/\/ A map links each word to how many times we saw it.\n    count := map[string]int{}\n    scanner := bufio.NewScanner(file)\n    scanner.Split(bufio.ScanWords) \/\/ one word per Scan, not one line\n    for scanner.Scan() {\n        word := strings.ToLower(scanner.Text()) \/\/ ignore upper and lower case\n        count[word]++\n    }\n\n    \/\/ Map order is random, so sort the keys before printing.\n    for _, word := range slices.Sorted(maps.Keys(count)) {\n        fmt.Println(word, count[word])\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>go 4\nrust 1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>bufio.ScanWords<\/code> changes the scanner to return words. Each word is made lower case and counted in the map. Combined, this is the standard answer to &#8220;count words in a file&#8221;.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">ReadFile vs bufio.Scanner in Go File Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Go file programs have two main ways to read a file. The diagram and table below compare them.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-diagram-2-1024x640.png\" alt=\"Go file programs comparison of os.ReadFile and bufio.Scanner\" class=\"wp-image-813\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-diagram-2-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-diagram-2-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-diagram-2-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-diagram-2-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-diagram-2-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">os.ReadFile loads the whole file into memory, while bufio.Scanner reads one line at a time with little memory.<\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>os.ReadFile<\/th><th>bufio.Scanner<\/th><\/tr><\/thead><tbody><tr><td>Reads<\/td><td>Whole file at once<\/td><td>One line or word at a time<\/td><\/tr><tr><td>Memory<\/td><td>Equal to file size<\/td><td>Small, about 64 KB buffer<\/td><\/tr><tr><td>Code length<\/td><td>One line<\/td><td>A short loop<\/td><\/tr><tr><td>Big files (1 GB+)<\/td><td>Risky<\/td><td>Safe<\/td><\/tr><tr><td>Best for<\/td><td>Configs, small files<\/td><td>Logs, large data<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">So use <code>os.ReadFile<\/code> for small files and <code>bufio.Scanner<\/code> for anything that might grow large.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes in Go File Programs<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Forgetting to close:<\/strong> every <code>os.Open<\/code> or <code>os.Create<\/code> needs a <code>Close<\/code>, usually with <code>defer<\/code>.<\/li>\n\n\n<li><strong>Ignoring errors:<\/strong> a missing file or bad permission shows up only in the error value.<\/li>\n\n\n<li><strong>os.Create on an existing file:<\/strong> it empties the file first, so use <code>O_APPEND<\/code> to add lines.<\/li>\n\n\n<li><strong>Building paths with +:<\/strong> use <code>filepath.Join<\/code>, which uses the right slash for each OS.<\/li>\n\n\n<li><strong>Splitting CSV by commas:<\/strong> quoted fields break, so use <code>encoding\/csv<\/code>.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for Go File Programs<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Use defer f.Close()<\/strong> right after a successful open.<\/li>\n\n\n<li><strong>Read big files with bufio<\/strong>, never all at once.<\/li>\n\n\n<li><strong>Use 0644 for files and 0755 for folders<\/strong>, which are the common safe defaults.<\/li>\n\n\n<li><strong>Use os.MkdirTemp in tests<\/strong>, so tests never touch real user files.<\/li>\n\n\n<li><strong>Check scanner.Err()<\/strong> after every scanning loop.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Go File Programs Interview Questions and Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Interviewers ask these Go file programs more than any other file questions. Each program is complete, with real output from Go 1.27.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Read and Write Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q1. What is the difference between os.Create and os.OpenFile?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>os.Create<\/code> opens a file for writing, creates it if needed, and empties it if it exists. <code>os.OpenFile<\/code> lets you choose flags such as <code>O_APPEND<\/code>, <code>O_RDONLY<\/code> or <code>O_EXCL<\/code>, so you control exactly what happens.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q2. What does 0644 mean?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is a file permission in octal. The owner can read and write (6), and the group and others can only read (4 and 4). Folders often use 0755, so others can also open them.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q3. What does this program print?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"path\/filepath\"\n)\n\nfunc main() {\n    folder, _ := os.MkdirTemp(\"\", \"q3\")\n    defer os.RemoveAll(folder)\n    path := filepath.Join(folder, \"a.txt\")\n    os.WriteFile(path, []byte(\"first\"), 0644)\n    os.WriteFile(path, []byte(\"second\"), 0644) \/\/ replaces, does not append\n    data, _ := os.ReadFile(path)\n    fmt.Println(string(data))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>second<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>os.WriteFile<\/code> always replaces the content. To keep &#8220;first&#8221;, open the file with <code>O_APPEND<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q4. What does this program print?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    _, err := os.ReadFile(\"does-not-exist.txt\")\n    fmt.Println(err)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>open does-not-exist.txt: no such file or directory<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The error includes the operation, the path and the reason. That is why Go file errors are easy to debug.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Buffer and Performance Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q5. Why use bufio.Writer for many small writes?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"path\/filepath\"\n)\n\nfunc main() {\n    folder, _ := os.MkdirTemp(\"\", \"buf\")\n    defer os.RemoveAll(folder)\n    file, _ := os.Create(filepath.Join(folder, \"nums.txt\"))\n    defer file.Close()\n\n    writer := bufio.NewWriter(file) \/\/ collects writes in memory first\n    for i := 1; i &lt;= 1000; i++ {\n        fmt.Fprintln(writer, i) \/\/ Fprintln prints into the writer, not the screen\n    }\n    fmt.Println(\"buffered bytes before flush:\", writer.Buffered() &gt; 0)\n    writer.Flush() \/\/ write everything to the file in one go\n    info, _ := file.Stat()\n    fmt.Println(\"file size:\", info.Size())\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>buffered bytes before flush: true\nfile size: 3893<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Each <code>Fprintln<\/code> goes into memory, and <code>Flush<\/code> writes the whole buffer at once. If you forget <code>Flush<\/code>, the last part of your data is lost.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q6. What is the default line limit of bufio.Scanner?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">About 64 KB per line (<code>bufio.MaxScanTokenSize<\/code>). For longer lines, call <code>scanner.Buffer<\/code> with a bigger buffer, or use <code>bufio.Reader.ReadString<\/code> instead.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q7. Why should you defer Close right after the error check?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you defer before checking the error, you may call <code>Close<\/code> on a nil file. If you defer much later, an early <code>return<\/code> can skip it and leak the file handle.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Path and Folder Questions on Go File Programs<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q8. What does this program print?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"path\/filepath\"\n)\n\nfunc main() {\n    path := filepath.Join(\"data\", \"2026\", \"report.csv\")\n    \/\/ Base is the file name, Ext is the extension, Dir is the folder part.\n    fmt.Println(filepath.Base(path), filepath.Ext(path), filepath.Dir(path))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>report.csv .csv data\/2026<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">On Windows, <code>Dir<\/code> would show <code>data\\2026<\/code>, because <code>filepath<\/code> uses the right separator for each OS.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q9. How do you create nested folders?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>os.MkdirAll(\"logs\/2026\/oct\", 0755)<\/code>. It creates every missing folder on the path and does nothing if they already exist.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q10. How do you walk every file under a folder?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"io\/fs\"\n    \"os\"\n    \"path\/filepath\"\n)\n\nfunc main() {\n    folder, _ := os.MkdirTemp(\"\", \"walk\")\n    defer os.RemoveAll(folder)\n    os.MkdirAll(filepath.Join(folder, \"src\", \"util\"), 0755)\n    os.WriteFile(filepath.Join(folder, \"src\", \"main.go\"), nil, 0644)\n    os.WriteFile(filepath.Join(folder, \"src\", \"util\", \"str.go\"), nil, 0644)\n\n    \/\/ WalkDir visits every file and folder in name order.\n    \/\/ It calls this small function once for each entry it finds.\n    filepath.WalkDir(folder, func(path string, entry fs.DirEntry, err error) error {\n        if !entry.IsDir() { \/\/ ! means \"not\", so this skips folders\n            relativePath, _ := filepath.Rel(folder, path) \/\/ path inside our folder\n            fmt.Println(relativePath)\n        }\n        return nil \/\/ nil means \"keep walking\"\n    })\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>src\/main.go\nsrc\/util\/str.go<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>filepath.WalkDir<\/code> goes through every folder level for you. For each entry, the small function skips folders and prints files. <code>filepath.Rel<\/code> cuts off the temporary folder part, so the output stays short.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q11. How do you embed a file into your Go binary?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use the <code>embed<\/code> package with a <code>\/\/go:embed config.json<\/code> comment above a <code>string<\/code>, <code>[]byte<\/code> or <code>embed.FS<\/code> variable. The file then ships inside the binary, so you do not need it on disk at run time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q12. Is os.ReadFile safe for a 2 GB log file?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No. It loads all 2 GB into memory, which can crash small servers. Use <code>bufio.Scanner<\/code> or <code>io.Copy<\/code> so only a small part is in memory at a time.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Task<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This task combines several Go file programs from above. Write a program that reads a log file and writes only the lines containing &#8220;ERROR&#8221; into a new file called <code>errors.log<\/code>, then prints how many lines it copied. Hint: open the source with <code>os.Open<\/code>, the target with <code>os.Create<\/code>, and use <code>bufio.Scanner<\/code> with <code>strings.Contains<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Official Resources<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/pkg.go.dev\/os\">os package documentation<\/a><\/li>\n\n\n<li><a href=\"https:\/\/pkg.go.dev\/bufio\">bufio package documentation<\/a><\/li>\n\n\n<li><a href=\"https:\/\/pkg.go.dev\/encoding\/csv\">encoding\/csv package documentation<\/a><\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Quick Recap<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Go file programs open, read or write, and close files, checking every error.<\/li>\n\n\n<li><code>os.WriteFile<\/code> and <code>os.ReadFile<\/code> are simple for small files.<\/li>\n\n\n<li><code>bufio.Scanner<\/code> reads big files line by line with little memory.<\/li>\n\n\n<li>Use <code>O_APPEND<\/code> to add to a file, because <code>os.Create<\/code> empties it.<\/li>\n\n\n<li>Use <code>filepath.Join<\/code>, <code>encoding\/csv<\/code> and <code>defer Close<\/code> for safe, portable code.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Next, we turn Go data into JSON and back. Read <a href=\"https:\/\/smitabharat.com\/blog\/go-json-programs\/\">Go JSON programs with output<\/a>, with marshal, unmarshal, nested JSON and struct tags. For the theory, see the <a href=\"https:\/\/smitabharat.com\/blog\/go-file-handling-examples\/\">Go file handling guide<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Go file programs read, write and manage files on disk, such as saving a report, loading a config or counting lines in a log.&hellip;<\/p>\n","protected":false},"author":1,"featured_media":811,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_swapz_level":"","_swapz_series_part":0,"_swapz_hide_toc":false,"_swapz_hide_featured":false,"_swapz_description":"","footnotes":""},"categories":[106],"tags":[96,43,95,11,104],"swapz_series":[],"class_list":["post-814","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-go-programs","tag-beginner","tag-go-file-handling","tag-go-interview-questions","tag-go-lang","tag-go-programs"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Go File Programs: Read, Write, Append and Walk<\/title>\n<meta name=\"description\" content=\"Go file programs with output: read and write files, append logs, read line by line, CSV, file info and folder walk, plus file interview questions.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/smitabharat.com\/blog\/go-file-programs\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Go File Programs: Read, Write, Append and Walk\" \/>\n<meta property=\"og:description\" content=\"Go file programs with output: read and write files, append logs, read line by line, CSV, file info and folder walk, plus file interview questions.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/smitabharat.com\/blog\/go-file-programs\/\" \/>\n<meta property=\"og:site_name\" content=\"Smita Bharat - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2026-10-08T09:30:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-11-28T19:59:30+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-featured.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2400\" \/>\n\t<meta property=\"og:image:height\" content=\"1260\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Smita\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Smita\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"20 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-file-programs\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-file-programs\\\/\"},\"author\":{\"name\":\"Smita\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"headline\":\"Go File Programs with Output: Read, Write, Append and Walk\",\"datePublished\":\"2026-10-08T09:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:30+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-file-programs\\\/\"},\"wordCount\":1864,\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-file-programs\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-file-programs-featured.png\",\"keywords\":[\"Beginner\",\"Go File Handling\",\"Go Interview Questions\",\"Go Lang\",\"Go Programs\"],\"articleSection\":[\"Go Programs\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-file-programs\\\/\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-file-programs\\\/\",\"name\":\"Go File Programs: Read, Write, Append and Walk\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-file-programs\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-file-programs\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-file-programs-featured.png\",\"datePublished\":\"2026-10-08T09:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:30+00:00\",\"description\":\"Go file programs with output: read and write files, append logs, read line by line, CSV, file info and folder walk, plus file interview questions.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-file-programs\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-file-programs\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-file-programs\\\/#primaryimage\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-file-programs-featured.png\",\"contentUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-file-programs-featured.png\",\"width\":2400,\"height\":1260,\"caption\":\"Go File Programs featured image: read, write and folder walk output\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-file-programs\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Go File Programs with Output: Read, Write, Append and Walk\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\",\"name\":\"Smita Bharat Blog\",\"description\":\"Golang &amp; Backend Development Tutorials and Interview Questions\",\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"alternateName\":\"Smita Bharat\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\",\"name\":\"Smita\",\"logo\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/smitabharat.com\\\/blog\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Go File Programs: Read, Write, Append and Walk","description":"Go file programs with output: read and write files, append logs, read line by line, CSV, file info and folder walk, plus file interview questions.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/smitabharat.com\/blog\/go-file-programs\/","og_locale":"en_US","og_type":"article","og_title":"Go File Programs: Read, Write, Append and Walk","og_description":"Go file programs with output: read and write files, append logs, read line by line, CSV, file info and folder walk, plus file interview questions.","og_url":"https:\/\/smitabharat.com\/blog\/go-file-programs\/","og_site_name":"Smita Bharat - Blog","article_published_time":"2026-10-08T09:30:00+00:00","article_modified_time":"2026-11-28T19:59:30+00:00","og_image":[{"width":2400,"height":1260,"url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-featured.png","type":"image\/png"}],"author":"Smita","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Smita","Est. reading time":"20 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/smitabharat.com\/blog\/go-file-programs\/#article","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/go-file-programs\/"},"author":{"name":"Smita","@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"headline":"Go File Programs with Output: Read, Write, Append and Walk","datePublished":"2026-10-08T09:30:00+00:00","dateModified":"2026-11-28T19:59:30+00:00","mainEntityOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-file-programs\/"},"wordCount":1864,"publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-file-programs\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-featured.png","keywords":["Beginner","Go File Handling","Go Interview Questions","Go Lang","Go Programs"],"articleSection":["Go Programs"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/smitabharat.com\/blog\/go-file-programs\/","url":"https:\/\/smitabharat.com\/blog\/go-file-programs\/","name":"Go File Programs: Read, Write, Append and Walk","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-file-programs\/#primaryimage"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-file-programs\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-featured.png","datePublished":"2026-10-08T09:30:00+00:00","dateModified":"2026-11-28T19:59:30+00:00","description":"Go file programs with output: read and write files, append logs, read line by line, CSV, file info and folder walk, plus file interview questions.","breadcrumb":{"@id":"https:\/\/smitabharat.com\/blog\/go-file-programs\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/smitabharat.com\/blog\/go-file-programs\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/smitabharat.com\/blog\/go-file-programs\/#primaryimage","url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-featured.png","contentUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-file-programs-featured.png","width":2400,"height":1260,"caption":"Go File Programs featured image: read, write and folder walk output"},{"@type":"BreadcrumbList","@id":"https:\/\/smitabharat.com\/blog\/go-file-programs\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/smitabharat.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Go File Programs with Output: Read, Write, Append and Walk"}]},{"@type":"WebSite","@id":"https:\/\/smitabharat.com\/blog\/#website","url":"https:\/\/smitabharat.com\/blog\/","name":"Smita Bharat Blog","description":"Golang &amp; Backend Development Tutorials and Interview Questions","publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"alternateName":"Smita Bharat","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/smitabharat.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339","name":"Smita","logo":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/image\/"},"sameAs":["https:\/\/smitabharat.com\/blog"]}]}},"_links":{"self":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/814","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/comments?post=814"}],"version-history":[{"count":1,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/814\/revisions"}],"predecessor-version":[{"id":892,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/814\/revisions\/892"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media\/811"}],"wp:attachment":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media?parent=814"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/categories?post=814"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/tags?post=814"},{"taxonomy":"swapz_series","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/swapz_series?post=814"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}