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
  • Read JSON file using Python

    import json
    import uuid
     
    jsonString = '{"firstname": "John", "lastname": "Doe"}'
    
    # Create random file name and write json to file
    filename = str(uuid.uuid4())
    
    with open(filename, "w") as f:
        f.write(jsonString)
    
    # Parse JSON string
    # Deserializes json string into dict
    print("Parse JSON string")
    jsonDict = json.loads(jsonString)
    
    # Iterating through the json
    for key, value in jsonDict.items():
        print(key, value)
    
    print()
    #----------------------------------------------------#
    
    print("Read JSON file")
    f = open (filename, "r")
     
    # Reading from file
    jsonDict = json.loads(f.read())
     
    # Iterating through the json
    for key, value in jsonDict.items():
        print(key, value)
     
    # Closing file
    f.close()
    
    # Output
    # Parse JSON string
    # firstname John
    # lastname Doe
    #
    # Read JSON file
    # firstname John
    # lastname Doe

    This exampleillustrates how to read from both a string and a JSON file. Initially, we have a JSON string stored in the variable 'jsonString'. We convert this JSON string into a Python dictionary using json.loads() method, which is then stored in the variable 'jsonDict'. Next, we read a JSON string stored in a file using json.loads(). To achieve this, we first convert the JSON file into a string using file handling, similar to the previous example. Then, we convert it into a string using the read() function. The subsequent steps mirror those followed earlier, utilizing the json.loads() method.

  • 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.