Basic Python

with as, open, dump, load, contextlib

Naranjito 2020. 12. 26. 23:28
Python    -> JSON 
list, tuple -> array
                ⇡dump, dumps
                Serialization, Encoding

We can say writing JSON file over the Python format
JSON -> Python
array   -> list
            ⇡load, loads
             Deserialization, Decoding

We can say reading JSON file over the Python format
import json

student_data = {
    "1.FirstName": "Gildong",
    "2.LastName": "Hong",
    "3.Age": 20, 
    "4.University": "Yonsei University",
    "5.Courses": [
        {
            "Major": "Statistics", 
            "Classes": ["Probability", 
                        "Generalized Linear Model", 
                        "Categorical Data Analysis"]
        }, 
        {
            "Minor": "ComputerScience", 
            "Classes": ["Data Structure", 
                        "Programming", 
                        "Algorithms"]
        }
    ]
} 

with open('student_file.json', 'w') as json_file:
  json.dump(student_data,json_file)

'w' : Write mode

 

with A as B : execute A and then save A as B. For example,

with open("student_file.json", "w") : open the "student_file.json" file with write mode

 

json.dump or jumps : serialize(encoding) the python to json.

dump : save JSON format file in the disk

dumps : using JSON format data in code editor

For example,

json.dump(student_data, json_file) : serialize(encoding) "student_data" python to json_file(will be written in json)

json.dumps(student_data) : using "student_data" data on the code editor continually 

 

data = {
    "president": {
        "name": "Zaphod Beeblebrox",
        "species": "Betelgeusian"
    }
}

with open("data_file.json", "w") as write_file:
    json.dump(data, write_file)
    
json.dumps(data)
>>>
{"president": {"name": "Zaphod Beeblebrox", "species": "Betelgeusian"}}

json.dumps(data, indent=4)
>>>
{
    "president": {
        "name": "Zaphod Beeblebrox",
        "species": "Betelgeusian"
    }
}

 

indent : JSON array elements and object members will be pretty-printed with that indent level.

sort_keys : If it is true (default: False), then the output of dictionaries will be sorted by key.

st_json=json.dumps(student_data, indent=4, sort_keys=True)
st_json

>>>
{
    "1.FirstName": "Gildong",
    "2.LastName": "Hong",
    "3.Age": 20,
    "4.University": "Yonsei University",
    "5.Courses": [
        {
            "Classes": [
                "Probability",
                "Generalized Linear Model",
                "Categorical Data Analysis"
            ],
            "Major": "Statistics"
        },
        {
            "Classes": [
                "Data Structure",
                "Programming",
                "Algorithms"
            ],
            "Minor": "ComputerScience"
        }
    ]
}

 

'r' : Read mode

 

json.load or loads : deserialize(decoding) json to python.

load : save python format file in the disk

loads : using python format data in code editor

For example,

json.load(st_json) : deserialize(decoding) "st_json" json_file to python

json.loads(st_json3) : using "st_json3" data on the code editor continually 

with open('student_file.json','r') as st_json:
  st_python=json.load(st_json)
st_python
>>>
{'1.FirstName': 'Gildong',
 '2.LastName': 'Hong',
 '3.Age': 20,
 '4.University': 'Yonsei University',
 '5.Courses': [{'Classes': ['Probability',
    'Generalized Linear Model',
    'Categorical Data Analysis'],
   'Major': 'Statistics'},
  {'Classes': ['Data Structure', 'Programming', 'Algorithms'],
   'Minor': 'ComputerScience'}]}
st_python2=json.loads(st_json3)
st_python2
>>>
{'1.FirstName': 'Gildong',
 '2.LastName': 'Hong',
 '3.Age': 20,
 '4.University': 'Yonsei University',
 '5.Courses': [{'Classes': ['Probability',
    'Generalized Linear Model',
    'Categorical Data Analysis'],
   'Major': 'Statistics'},
  {'Classes': ['Data Structure', 'Programming', 'Algorithms'],
   'Minor': 'ComputerScience'}]}

 

  • contextlib

It automate calls close method within the class. So it implements close method when it used with with.

from contextlib import closing

class OpenClose:
    def open(self):
        print('start the work')

    def do_something(self):
        print('emplementing the work')
        print('emplementing the work')

    def close(self):
        print('terminate the work')

class doOpenClose():
    with closing(OpenClose()) as f:
        f.open()
        f.do_something()
        
>>>
start the work
emplementing the work
emplementing the work
terminate the work

 

TIPS

  • r: Opens the file in read-only mode. Starts reading from the beginning of the file and is the default mode for the open() function.
  • rb: Opens the file as read-only in binary format and starts reading from the beginning of the file. While binary format can be used for different purposes, it is usually used when dealing with things like images, videos, etc.
  • r+: Opens a file for reading and writing, placing the pointer at the beginning of the file.
  • w: Opens in write-only mode. The pointer is placed at the beginning of the file and this will overwrite any existing file with the same name. It will create a new file if one with the same name doesn't exist.
  • wb: Opens a write-only file in binary mode.
  • w+: Opens a file for writing and reading.
  • wb+: Opens a file for writing and reading in binary mode.
  • a: Opens a file for appending new information to it. The pointer is placed at the end of the file. A new file is created if one with the same name doesn't exist.
  • ab: Opens a file for appending in binary mode.
  • a+: Opens a file for both appending and reading.
  • ab+: Opens a file for both appending and reading in binary mode.

 

reference

- https://stackabuse.com/file-handling-in-python/