python-3.xhome-assistant

Do anyone know how to read files in home assistant?


I am creating a python file in home assistant using hacs-pyscript. In that file I want to read a json file to get its data. But while using the open() function it is generating an error and showing that name 'open' is not defined. Is there any method to read a file in home assistant which is present at a particular location?

Here is my code:-

import json
import logging

from pymongo import MongoClient

# Creating an object
logger = logging.getLogger()

URI = "mongodb://localhost:27017"
client = MongoClient(URI)
logger.info("Working 1...")

db = client["local_db"]
col = db["devices"]

logger.info("Working 2...")

file = open("/config/.storage/core.device_registry")

logger.info("Working 3...")

Here is the screenshot of the error:- enter image description here


Solution

  • I have found the answer. We will have to use the "os" library and its function "os.open()" to open the file in read mode.

    Here is the code that we can use:-

    import json
    import logging
    import os
    
    from pymongo import MongoClient
    
    # Creating an object
    logger = logging.getLogger()
    
    URI = "mongodb://localhost:27017"
    client = MongoClient(URI)
    logger.info("Working 1...")
    
    db = client["local_db"]
    col = db["devices"]
    
    logger.info("Working 2...")
    
    # file = open("/config/.storage/core.device_registry")
    f = os.open("/config/.storage/core.device_registry", os.O_RDONLY)
    data = os.read(f, 200000)
    myStr = data.decode("UTF-8")
    
    
    
    logger.info(myStr)
    
    logger.info("Working 3...")