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.

4 snippets
  • Create temporary file or directory in Go

    package main
    
    import (
        "fmt"
        "os"
        "path/filepath"
    )
    
    func checkErr(err error) {
        if err != nil {
            panic(err)
        }
    }
    
    func main() {
        // The simplest way to create a temporary file is to call os.CreateTemp.
        // It will create and open the file for reading and writing.
        // We used "" as the first argument, so os.CreateTemp will create a file in the default directory.
        tmpFile, err := os.CreateTemp("", "tmpfile")
        checkErr(err)
        defer os.Remove(tmpFile.Name())
    
        fmt.Println("Temp file name:", tmpFile.Name())
    
        // Write some data to the temporary file
        _, err = tmpFile.Write([]byte{1, 2, 3, 4, 5})
        checkErr(err)
    
        // If we intend to write a lot of temporary files, we may prefer to create a temporary directory.
        // The arguments to os.MkdirTemp are the same as for os.CreateTemp, but it returns the directory name rather than the opened file.
        dName, err := os.MkdirTemp("", "tmpdir")
        checkErr(err)
        defer os.RemoveAll(dName)
        
        fmt.Println("Temp directory name:", dName)
    
        fName := filepath.Join(dName, "testFile")
        err = os.WriteFile(fName, []byte{1, 2, 3, 4, 5}, 0666)
        checkErr(err)
        defer os.Remove(fName)
    }
    
    // Output:
    // Temp file name: /tmp/tmpfile3400905374
    // Temp directory name: /tmp/tmpdir2812568099

    During program execution, we often want to create data that is not needed after the program exits. Temporary files and directories are useful for this purpose because they do not pollute the file system over time.

  • 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")
    print(f.read())
    f.close()
    os.remove(filename)
    
    # 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.

  • Read a file line by line in Python

    import os
    import uuid
    
    filename = str(uuid.uuid4()) # create random file name
    wLines = ["First line\n", "Second line\n", "Third line\n"]
    
    # writing lines to file
    f = open(filename, 'w')
    f.writelines(wLines)
    f.close()
    
    #--------------------------------------------------------#
    
    print("-----Read lines using 'readlines' method-----")
    f = open(filename, 'r')
    rLines = f.readlines()
    
    for lineNumber, line in enumerate(rLines, 1):
    	print("Line {}: {}".format(lineNumber, line.strip()))
    
    #--------------------------------------------------------#
    
    print("-----Read lines using 'readline' method-----")
    f = open(filename, 'r')
    lineNumber = 1
     
    while True:
        lineNumber += 1
     
        # Get next line from file
        line = f.readline()
     
        # if line is empty
        # end of file is reached
        if not line:
            break
        print("Line {}: {}".format(lineNumber, line.strip()))
     
    f.close()
    
    #--------------------------------------------------------#
    
    print("-----Read lines via file object iteration-----")
    f = open(filename, 'r')
    
    for lineNumber, line in enumerate(f, 1):
        print("Line {}: {}".format(lineNumber, line.strip()))
    
    #--------------------------------------------------------#
    
    print("-----Read lines via file contex manager-----")
    with open(filename, "r") as f:
        for lineNumber, line in enumerate(f, 1):
            print("Line {}: {}".format(lineNumber, line.strip()))
    
    os.remove(filename) # remove file
    
    # Output example:
    
    # Read lines using 'readlines' method
    # Line 1: First line
    # Line 2: Second line
    # Line 3: Third line

    Here's an example of reading from a file line by line in Python.

  • Writing files in Go

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

    Here are examples of writing data to files using Go.