Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

2 snippets
  • Writing JSON to a file in Python

    import json
    import os
    import uuid
    filename = str(uuid.uuid4()) # create random file name
    # JSON data to be written
    jsonDict ={
        "firstname" : "John",
        "lastname" : "Doe",
        "age" : 30,
        "phonenumber" : "9976770500"
    # write JSON to file
    with open(filename, "w") as f:
        json.dump(jsonDict, f)
    # read JSON string from file
    f = open(filename, "r")
    # Output:
    # {"firstname": "John", "lastname": "Doe", "age": 30, "phonenumber": "9976770500"}

    You can write JSON to a file using the json.dump() function from the JSON module combined with file handling in Python. In thisexample, we open a file in writing mode. If the file doesn't exist, it will be created. The json.dump() function converts the Python dictionary into a JSON string, which is then saved in the file.

  • Writing files in Go

    package main
    import (
    func checkErr(err error) {
        if err != nil {
    func main() {
        content := "Some content"
        // write a string (or just bytes) into a file
        err := os.WriteFile("/tmp/dfile1", []byte(content), 0644)
        // open a file for writing
        file, err := os.Create("/tmp/dfile2")
        // defer a Close immediately after opening a file
        defer file.Close()
        bytesCount, err := file.Write([]byte(content))
        fmt.Printf("wrote %d bytes\n", bytesCount)
        bytesCount, err = file.WriteString("Some other content\n")
        fmt.Printf("wrote %d bytes\n", bytesCount)
        // flush writes to a stable storage (file system for example)
        // bufio provides buffered writers
        writer := bufio.NewWriter(file)
        bytesCount, err = writer.WriteString("Some othe buffered content\n")
        fmt.Printf("wrote %d bytes\n", bytesCount)
        // ensure all buffered operations have been applied to the underlying writer

    Here are examples of writing data to files using Go.