Example #1
0
def read(path, linea_inicio=0, total_lineas=None):
    """
    Lee el contenido de un archivo y devuelve los datos
    @param path: ruta del fichero
    @type path: str
    @param linea_inicio: primera linea a leer del fichero
    @type linea_inicio: int positivo
    @param total_lineas: numero maximo de lineas a leer. Si es None o superior al total de lineas se leera el
        fichero hasta el final.
    @type total_lineas: int positivo
    @rtype: str
    @return: datos que contiene el fichero
    """
    path = encode(path)
    try:
        if path.lower().startswith("smb://"):
            f = samba.smb_open(path, "rb")
        else:
            f = open(path, "rb")

        data = []
        for x, line in enumerate(f):
            if x < linea_inicio: continue
            if len(data) == total_lineas: break
            data.append(line)
        f.close()
    except:
        logger.error("ERROR al leer el archivo: %s" % path)
        logger.error(traceback.format_exc())
        return False

    else:
        return "".join(data)
Example #2
0
def write(path, data):
    """
    Guarda los datos en un archivo
    @param path: ruta del archivo a guardar
    @type path: str
    @param data: datos a guardar
    @type data: str
    @rtype: bool
    @return: devuelve True si se ha escrito correctamente o False si ha dado un error
    """
    path = encode(path)
    try:
        if path.lower().startswith("smb://"):
            f = samba.smb_open(path, "wb")
        else:
            f = open(path, "wb")

        f.write(data)
        f.close()
    except:
        logger.error("ERROR al guardar el archivo: %s" % path)
        logger.error(traceback.format_exc())
        return False
    else:
        return True
def write(path, data):
    """
    Guarda los datos en un archivo
    @param path: ruta del archivo a guardar
    @type path: str
    @param data: datos a guardar
    @type data: str
    @rtype: bool
    @return: devuelve True si se ha escrito correctamente o False si ha dado un error
    """
    path = encode(path)
    try:
        if path.lower().startswith("smb://"):
            f = samba.smb_open(path, "wb")
        else:
            f = open(path, "wb")
            
        f.write(data)
        f.close()
    except:
        logger.error("ERROR al guardar el archivo: %s" %(path))
        logger.error(traceback.format_exc())
        return False
    else:
        return True
Example #4
0
def file_open(path, mode="r", silent=False, vfs=True):
    """
    Abre un archivo
    @param path: ruta
    @type path: str
    @rtype: str
    @return: objeto file
    """
    path = encode(path)
    try:
        if xbmc_vfs and vfs:
            if 'r' in mode and '+' in mode:
                mode = mode.replace('r', 'w').replace('+', '')
                logger.debug('Open MODE cambiado a: %s' % mode)
            if 'a' in mode:
                mode = mode.replace('a', 'w').replace('+', '')
                logger.debug('Open MODE cambiado a: %s' % mode)
            return xbmcvfs.File(path, mode)
        elif path.lower().startswith("smb://"):
            return samba.smb_open(path, mode)
        else:
            return open(path, mode)
    except:
        logger.error("ERROR al abrir el archivo: %s, %s" % (path, mode))
        if not silent:
            logger.error(traceback.format_exc())
            platformtools.dialog_notification("Error al abrir", path)
        return False
def read(path, linea_inicio=0, total_lineas=None):
    """
    Lee el contenido de un archivo y devuelve los datos
    @param path: ruta del fichero
    @type path: str
    @param linea_inicio: primera linea a leer del fichero
    @type linea_inicio: int positivo
    @param total_lineas: numero maximo de lineas a leer. Si es None o superior al total de lineas se leera el
        fichero hasta el final.
    @type total_lineas: int positivo
    @rtype: str
    @return: datos que contiene el fichero
    """
    path = encode(path)
    try:
        if path.lower().startswith("smb://"):
            f = samba.smb_open(path, "rb")
        else:
            f = open(path, "rb")

        data = []
        for x, line in enumerate(f):
            if x < linea_inicio: continue
            if len(data) == total_lineas: break
            data.append(line)
        f.close()
    except:
        logger.error("ERROR al leer el archivo: %s" %(path))
        logger.error(traceback.format_exc())
        return False
    
    else:
        return "".join(data)
Example #6
0
def write(path, data, mode="wb", silent=False, vfs=True):
    """
    Guarda los datos en un archivo
    @param path: ruta del archivo a guardar
    @type path: str
    @param data: datos a guardar
    @type data: str
    @rtype: bool
    @return: devuelve True si se ha escrito correctamente o False si ha dado un error
    """
    path = encode(path)
    try:
        if xbmc_vfs and vfs:
            f = xbmcvfs.File(path, mode)
            result = f.write(data)
            f.close()
            return bool(result)
        elif path.lower().startswith("smb://"):
            f = samba.smb_open(path, mode)
        else:
            f = open(path, mode)

        f.write(data)
        f.close()
    except:
        logger.error("ERROR al guardar el archivo: %s" % path)
        if not silent:
            logger.error(traceback.format_exc())
        return False
    else:
        return True
Example #7
0
def file_open(path, mode="r", silent=False, vfs=True):
    """
    Open a file
    @param path: path
    @type path: str
    @rtype: str
    @return: file object
    """
    path = encode(path)
    try:
        if xbmc_vfs and vfs:
            if 'r' in mode and '+' in mode:
                mode = mode.replace('r', 'w').replace('+', '')
                logger.debug('Open MODE changed to: %s' % mode)
            if 'a' in mode:
                mode = mode.replace('a', 'w').replace('+', '')
                logger.debug('Open MODE changed to: %s' % mode)
            return xbmcvfs.File(path, mode)
        elif path.lower().startswith("smb://"):
            return samba.smb_open(path, mode)
        else:
            if fileIo:
                return io.FileIO(path, mode)
            else:
                # return io.open(path, mode, decode='utf-8')
                return open(path, mode)
    except:
        logger.error("ERROR when opening file: %s, %s" % (path, mode))
        if not silent:
            logger.error(traceback.format_exc())
            platformtools.dialog_notification("Error Opening", path)
        return False
Example #8
0
def write(path, data, mode="w", silent=False, vfs=True):
    """
    Save the data to a file
    @param path: file path to save
    @type path: str
    @param data: data to save
    @type data: str
    @rtype: bool
    @return: returns True if it was written correctly or False if it gave an error
    """
    path = encode(path)
    try:
        if xbmc_vfs and vfs:
            f = xbmcvfs.File(path, mode)
            result = f.write(data)
            f.close()
            return bool(result)
        elif path.lower().startswith("smb://"):
            f = samba.smb_open(path, mode)
        else:
            f = open(path, mode)

        f.write(data)
        f.close()
    except:
        logger.error("ERROR saving file: %s" % path)
        if not silent:
            logger.error(traceback.format_exc())
        return False
    else:
        return True
Example #9
0
def write(path, data, mode="wb", silent=False, vfs=True, ch_mod=''):
    """
    Guarda los datos en un archivo
    @param path: ruta del archivo a guardar
    @type path: str
    @param data: datos a guardar
    @type data: str, bytes, bytesarray
    @rtype: bool
    @return: devuelve True si se ha escrito correctamente o False si ha dado un error
    """
    path = encode(path)
    try:
        mode_open = mode.replace('s', '')
        if xbmc_vfs and vfs:
            if 'r' in mode and '+' in mode:
                mode = mode.replace('r', 'w').replace('+', '')
                mode_open = mode.replace('r', 'w').replace('+', '')
                logger.debug('Open MODE cambiado a: %s' % mode)
            if 'a' in mode:
                mode = mode.replace('a', 'w').replace('+', '')
                mode_open = mode.replace('a', 'w').replace('+', '')
                logger.debug('Open MODE cambiado a: %s' % mode)

            if mode not in ['w', 'a'] and PY3 and isinstance(data, str):
                data = bytearray(list(ord(x) for x in data))
            elif isinstance(data, bytes):
                data = bytearray(data)
            f = xbmcvfs.File(path, mode_open)
            result = bool(f.write(data))
            f.close()
            if result and ch_mod:
                result = chmod(path, ch_mod, silent=silent)
            return result

        elif path.lower().startswith("smb://"):
            f = samba.smb_open(path, "wb")

        elif PY3 and mode in ['w', 'a']:
            f = open(path, mode_open, encoding=fs_encoding)
        else:
            f = open(path, mode_open)

        if mode not in ['w', 'a'] and PY3 and isinstance(data, str):
            data = bytes(list(ord(x) for x in data))

        f.write(data)
        f.close()
    except:
        logger.error("ERROR al guardar el archivo: %s" % path)
        logger.error(traceback.format_exc())
        try:
            f.close()
        except:
            pass
        return False
    else:
        return True
Example #10
0
def file_open(path, mode="r"):
    """
    Abre un archivo
    @param path: ruta
    @type path: str
    @rtype: str
    @return: objeto file
    """
    path = encode(path)
    try:
        if path.lower().startswith("smb://"):
            return samba.smb_open(path, mode)
        else:
            return open(path, mode)
    except:
        logger.error("ERROR al abrir el archivo: %s" % path)
        logger.error(traceback.format_exc())
        platformtools.dialog_notification("Error al abrir", path)
        return False
def file_open(path, mode="r"):
    """
    Abre un archivo
    @param path: ruta
    @type path: str
    @rtype: str
    @return: objeto file
    """
    path = encode(path)
    try:
      if path.lower().startswith("smb://"):
          return samba.smb_open(path, mode)
      else:
          return open(path, mode)
    except:
      logger.error("ERROR al abrir el archivo: %s" %(path))
      logger.error(traceback.format_exc())
      platformtools.dialog_notification("Error al abrir", path)
      return False
Example #12
0
def read(path,
         linea_inicio=0,
         total_lineas=None,
         whence=0,
         silent=False,
         vfs=True):
    """
    Lee el contenido de un archivo y devuelve los datos
    @param path: ruta del fichero
    @type path: str
    @param linea_inicio: primera linea a leer del fichero
    @type linea_inicio: int positivo
    @param total_lineas: numero maximo de lineas a leer. Si es None o superior al total de lineas se leera el
        fichero hasta el final.
    @type total_lineas: int positivo
    @rtype: str
    @return: datos que contiene el fichero
    """
    path = encode(path)
    try:
        if type(linea_inicio) != int:
            try:
                linea_inicio = int(linea_inicio)
            except:
                logger.error('Read: ERROR de linea_inicio: %s' %
                             str(linea_inicio))
                linea_inicio = 0
        if total_lineas != None and type(total_lineas) != int:
            try:
                total_lineas = int(total_lineas)
            except:
                logger.error('Read: ERROR de total_lineas: %s' %
                             str(total_lineas))
                total_lineas = None
        if xbmc_vfs and vfs:
            if not exists(path): return False
            f = xbmcvfs.File(path, "rb")
            if linea_inicio > 0:
                if type(whence) != int:
                    try:
                        whence = int(whence)
                    except:
                        return False
                f.seek(linea_inicio, whence)
                logger.debug('POSICIÓN de comienzo de lectura, tell(): %s' %
                             f.seek(0, 1))
            if total_lineas == None:
                total_lineas = 0
            data = f.read(total_lineas)
            return "".join(data)
        elif path.lower().startswith("smb://"):
            f = samba.smb_open(path, "rb")
        else:
            f = open(path, "rb")

        data = []
        for x, line in enumerate(f):
            if x < linea_inicio: continue
            if len(data) == total_lineas: break
            data.append(line)
        f.close()
    except:
        if not silent:
            logger.error("ERROR al leer el archivo: %s" % path)
            logger.error(traceback.format_exc())
        return False

    else:
        return "".join(data)
Example #13
0
def read(path,
         linea_inicio=0,
         total_lineas=None,
         whence=0,
         mode='r',
         silent=False,
         vfs=True):
    """
    Lee el contenido de un archivo y devuelve los datos
    @param path: ruta del fichero
    @type path: str
    @param linea_inicio: primera linea a leer del fichero
    @type linea_inicio: int positivo
    @param total_lineas: numero maximo de lineas a leer. Si es None o superior al total de lineas se leera el
        fichero hasta el final.
    @type total_lineas: int positivo
    @rtype: str, bytes, bytesarray
    @return: datos que contiene el fichero
    """
    path = encode(path)
    try:
        mode_open = mode.replace('s', '')
        if not isinstance(linea_inicio, int):
            try:
                linea_inicio = int(linea_inicio)
            except:
                logger.error('Read: ERROR de linea_inicio: %s' %
                             str(linea_inicio))
                linea_inicio = 0
        if total_lineas != None and not isinstance(total_lineas, int):
            try:
                total_lineas = int(total_lineas)
            except:
                logger.error('Read: ERROR de total_lineas: %s' %
                             str(total_lineas))
                total_lineas = None

        if xbmc_vfs and vfs:
            if 'r' in mode and '+' in mode:
                mode = mode.replace('r', 'w').replace('+', '')
                mode_open = mode.replace('r', 'w').replace('+', '')
                logger.debug('Open MODE cambiado a: %s' % mode)
            if 'a' in mode:
                mode = mode.replace('a', 'w').replace('+', '')
                mode_open = mode.replace('a', 'w').replace('+', '')
                logger.debug('Open MODE cambiado a: %s' % mode)

            if not exists(path): return False
            f = xbmcvfs.File(path, "rb")
            if linea_inicio > 0:
                if not isinstance(whence, int):
                    try:
                        whence = int(whence)
                    except:
                        return False
                f.seek(linea_inicio, whence)
                logger.debug('POSICIÓN de comienzo de lectura, tell(): %s' %
                             f.seek(0, 1))
            if total_lineas == None:
                total_lineas = 0
            if mode in ['r', 'ra']:
                try:
                    data = f.read(total_lineas)
                except Exception as e:
                    if "codec can't decode" in str(e):
                        mode = 'rbs'
                        f.seek(linea_inicio, whence)
                        logger.error(
                            str(e) +
                            '.  Intentaremos leerlo en "mode=rbs", bytes a string'
                        )
                    else:
                        raise Exception(e)
            if mode not in ['r', 'ra']:
                data = f.readBytes(total_lineas)
            f.close()
            if mode in ['r', 'ra']:
                return "".join(data)
            elif mode in ['rbs', 'rabs'] and isinstance(
                    data, (bytes, bytearray)):
                return "".join(chr(x) for x in data)
            elif mode in ['rb', 'rab'] and isinstance(data, bytearray):
                return bytes(data)
            else:
                return data

        elif path.lower().startswith("smb://"):
            f = samba.smb_open(path, "rb")

        elif PY3 and mode in ['r', 'ra']:
            f = open(path, mode_open, encoding=fs_encoding)
        else:
            f = open(path, mode_open)

        data = []
        for x, line in enumerate(f):
            if x < linea_inicio: continue
            if len(data) == total_lineas: break
            data.append(line)
        f.close()
    except:
        logger.error("ERROR al leer el archivo: %s" % path)
        if not silent:
            logger.error(traceback.format_exc())
        try:
            f.close()
        except:
            pass
        return False

    else:
        if not PY3 or mode in ['r', 'ra']:
            return "".join(data)
        elif mode in ['rbs', 'rabs'] and isinstance(data, (bytes, bytearray)):
            return "".join(chr(x) for x in data)
        else:
            return b"".join(data)
Example #14
0
def read(path,
         linea_inicio=0,
         total_lineas=None,
         whence=0,
         silent=False,
         vfs=True):
    """
    Read the contents of a file and return the data
    @param path: file path
    @type path: str
    @param linea_inicio: first line to read from the file
    @type linea_inicio: positive int
    @param total_lineas: maximum number of lines to read. If it is None or greater than the total lines, the file will be read until the end.
    @type total_lineas: positive int
    @rtype: str
    @return: data contained in the file
    """
    path = encode(path)
    try:
        if not isinstance(linea_inicio, int):
            try:
                linea_inicio = int(linea_inicio)
            except:
                logger.error('Read: Start_line ERROR: %s' % str(linea_inicio))
                linea_inicio = 0
        if total_lineas != None and not isinstance(total_lineas, int):
            try:
                total_lineas = int(total_lineas)
            except:
                logger.error('Read: ERROR of total_lineas: %s' %
                             str(total_lineas))
                total_lineas = None
        if xbmc_vfs and vfs:
            if not exists(path): return False
            f = xbmcvfs.File(path, "r")
            data = f.read()

            if total_lineas == None:
                total_lineas = 9999999999
            if linea_inicio > 0:
                if not isinstance(whence, int):
                    try:
                        whence = int(whence)
                    except:
                        return False
                data = '\n'.join(data.split('\n')[linea_inicio:total_lineas])

            return data
        elif path.lower().startswith("smb://"):
            f = samba.smb_open(path, "rb")
        else:
            f = open(path, "rb")

        data = []
        for x, line in enumerate(f):
            if x < linea_inicio: continue
            if len(data) == total_lineas: break
            data.append(line)
        f.close()
    except:
        if not silent:
            logger.error("ERROR reading file: %s" % path)
            logger.error(traceback.format_exc())
        return False

    else:
        if not PY3:
            return unicode("".join(data))
        else:
            return unicode(b"".join(data))