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.

7 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")
    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 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.

  • Context manager in Python

    # File management using context manager
    class FileManager():
        def __init__(self, filename, mode):
            self.filename = filename
            self.mode = mode
            self.file = None
      
        # The __enter__ method opens the file and returns a file object
        def __enter__(self):
            print('Open file: {}'.format(self.filename))
            self.file = open(self.filename, self.mode)
            return self.file
    
        # The __exit__ method takes care of closing the file on exiting the with block 
        def __exit__(self, etype, value, traceback):
            print('Close file: {}'.format(self.filename))
            self.file.close()
    
    # A FileManager object is created with test.txt as the filename and "write" mode
    # when __init__ method is executed
    with FileManager('test.txt', 'w') as f:
        f.write('First line\n')
        f.write('Second line\n')
    
    # The file is already closed thanks to the automatic call to the __exit__ method
    print('File closed: {}\n'.format(f.closed))
    
    with FileManager('test.txt', 'r') as f:
        for line in f:
            print(line.rstrip())
    
    # Output
    #Open file: test.txt
    #Close file: test.txt
    #File closed: True
    #
    #Open file: test.txt
    #First line
    #Second line
    #Close file: test.txt

    When creating context managers using classes, be sure to ensure that the class includes methods: __enter__() and __exit__(). The __enter__() method provides a resource to be managed, and __exit__() performs cleanup operations without returning any value. To understand the basic structure of building context managers using classes, let's look at a simple FileManager class for managing files.

  • Binary search algorithm in Python

    # Returns index of target in arr if present, else -1
    def binary_search(arr, target):
    	low = 0
    	high = len(arr) - 1
    
    	while low <= high:
    		# Check base case
    		mid = (high + low) // 2
    
    		# If element is smaller than mid, then it can only
    		# be present in left subarray
    		if arr[mid] > target:
    			high = mid - 1
    		# Else the element can only be present in right subarray
    		elif arr[mid] < target:
    			low = mid + 1
    		# If element is present at the middle itself
    		else:
    			return mid
    
    	# Element is not present in the array
    	return -1
    
    # Test array
    arr = [ 2, 3, 4, 10, 40 ]
    target = 10
    
    result = binary_search(arr, target)
    
    if result != -1:
    	print("Element is present at index", str(result))
    else:
    	print("Element is not present in array")

    Binary Search is a searching algorithm for finding an element's position in a sorted array. In this approach, the element is always searched in the middle of a portion of an array.

  • Implementation of the Quick Sort algorithm in Python

    def quick_sort(arr):
        if len(arr) <= 1:
            return arr
        else:
            pivot = arr[0]
            left = [x for x in arr[1:] if x <= pivot]
            right = [x for x in arr[1:] if x > pivot]
            return quick_sort(left) + [pivot] + quick_sort(right)
    
    # Example usage:
    input_array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
    sorted_array = quick_sort(input_array)
    
    print("Original Array:", input_array)
    print("Sorted Array:", sorted_array)
    

    In this code, the quick_sort function is a recursive implementation of the Quick Sort algorithm. The pivot element is chosen as the first element of the array, and elements are partitioned into two sub-arrays (left and right) based on their relationship to the pivot. The function is then called recursively on the left and right sub-arrays until the entire array is sorted.

  • CSV file handling in Python

    import csv
    
    # Writing to a CSV file
    with open('data.csv', 'w', newline='') as csvfile:
        fieldnames = ['name', 'age', 'city']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    
        writer.writeheader()
        writer.writerow({'name': 'John', 'age': 30, 'city': 'New York'})
        writer.writerow({'name': 'Alice', 'age': 25, 'city': 'London'})
    
    # Reading from a CSV file
    with open('data.csv', newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            print(row)

    Examples of code for writing to a csv file and reading from a csv file.