File I/O and Persistence

The following are examples of programs that demonstrate reading from and writing to JSON files using Python.

Listing 19 scripts/PYQT4/04_data/01_json/main.py
import json

data = {"name": "John", "age": 30, "city": "New York"}

# Saving data
with open("data.json", "w") as file:
    json.dump(data, file)

# Reading data
with open("data.json", "r") as file:
    loaded_data = json.load(file)
    print(loaded_data)

This program saves Python dictionary data into a JSON file and then reads the saved JSON file and displays its content.

  • The json.dump() function is used to store data in JSON format in a file.

  • The json.load() function is used to load and display data from a JSON file.

Listing 20 scripts/PYQT4/04_data/02_data_read/main.py
# -*- coding: utf-8 -*-

import sys
import json
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget

class TableApp(QMainWindow):
    def __init__(self):
        super(TableApp, self).__init__()

        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('Data from JSON')
        self.setGeometry(100, 100, 400, 300)

        layout = QVBoxLayout()

        # 데이터 로드
        with open("../01_json/data.json", "r") as file:
            data = json.load(file)

        # 표 생성
        table = QTableWidget(self)
        table.setRowCount(len(data))
        table.setColumnCount(2)
        table.setHorizontalHeaderLabels(['Key', 'Value'])

        for row, (key, value) in enumerate(data.items()):
            table.setItem(row, 0, QTableWidgetItem(str(key)))
            table.setItem(row, 1, QTableWidgetItem(str(value)))

        layout.addWidget(table)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = TableApp()
    window.show()
    sys.exit(app.exec_())

This program reads data stored in a JSON file and displays it on a PyQt table widget.

  • The TableApp class reads the saved JSON data and displays it in the QTableWidget.

  • Each row of the table displays a key and value from the JSON data.