How do I get the current directory of the file, using macro in python?

I need the current directory of the file, without the file name. I made a few attempts but failed.

# -*- coding: cp1252 -*-
from __future__ import unicode_literals
import uno

CTX = uno.getComponentContext()
SM = CTX.getServiceManager()
ODOC = XSCRIPTCONTEXT.getDocument()

def create_instance(name, with_context=False):
    if with_context:
        instance = SM.createInstanceWithContext(name, CTX)
    else:
        instance = SM.createInstance(name)
    return instance

def apsoConsole(event=None):
    """ 
        https://extensions.libreoffice.org/extensions/apso-alternative-script-organizer-for-python
    """
    create_instance("apso.python.script.organizer.impl")
    from apso_utils import console
    #console()
    console(BACKGROUND=0x0, FOREGROUND=0xD3D7CF)
    return

import os
def mytest(*args):
    apsoConsole()
    var4 = ''
    var1 = os.path.realpath(__file__)
    var2 = os.path.abspath(os.getcwd())
    var3 = ODOC.getURL()
    #var4 = ConvertFromURL(var3)
    
    print(var1, '\n')
    print(var2, '\n')
    print(var3, '\n')
    print(var4, '\n')

Result:

/home/MY_USER/vnd.sun.star.tdoc:/13/Scripts/python/Module.py

/home/MY_USER

file:///home/MY_USER/%C3%81rea%20de%20Trabalho/p3/testep3.ods


Complement

I will use information from an ods file to insert into an odt file using the py3o.template module (instaled via Zaz-pip - elmau/zaz-pip: Extension for install and admin Python Pip in LibreOffice. - zaz-pip - Git para Cuates)

The encoding I use is cp1252.
The macro will take the ods file directory and manipulate an odt template file that is in the same directory. And, especially on Linux, I need to provide the full path to the file.

On Linux my directory is written like this:

/home/MY_USER/Área de Trabalho/p3/Instituição

But when using “.getURL ()” the text is encoded as if it were a url and is displayed like this, replacing the non-utf-8 characters:

file:///home/MY_USER/%C3%81rea%20de%20Trabalho/p3/Institui%C3%A7%C3%A3o

But if I use this string like this:

/home/MY_USER/%C3%81rea%20de%20Trabalho/p3/Institui%C3%A7%C3%A3o

The operating system cannot find the directory. It only finds the directory if it is written that way

/home/MY_USER/Área de Trabalho/p3/Instituição

I am currently using the following code to do this, but I was wondering if there is anything more simple and direct.

# -*- coding: cp1252 -*-
from __future__ import unicode_literals
import uno

import os
import platform
import urllib.parse

CTX = uno.getComponentContext()
SM = CTX.getServiceManager()
ODOC = XSCRIPTCONTEXT.getDocument()


OS_PATAFORM = platform.system()
    
def mytest2(*args):
    full_path = os.path.dirname(ODOC.getURL())
    full_path_mod = full_path.replace('file:///', '')
    separator = '/'

    if OS_PATAFORM == 'Windows' :
        dir_path = f"""{full_path_mod}{separator}"""
    else:
        dir_path = f"""{separator}{full_path_mod}{separator}"""   

    dir_path = urllib.parse.unquote(dir_path)

Hello,

Found this:

    var3 = os.path.dirname(ODOC.getURL())

There are two problems with using .getURL ():

  • Make the urlencode when there are non-utf-8 characters in the string, ex:
    my path:

C:/Users/MY_USER/Desktop/p3/Instituição

After using the command ‘os.path.dirname (ODOC.getURL ())’

file:///C:/Users/MY_USER/Desktop/p3/Institui%C3%A7%C3%A3o

  • Add the string ‘file:///’ before the path

Is there an automated way to already display the file directory, without me having to manipulate this string?

Another problem with using .getURL() is that when manipulating the string I have to check if the operating system is Windows or Linux, because in Linux the directory starts ‘/’ and in Windows it doesn’t

I am not clear about your goal. Please edit the question to provide an example input and the desired result, perhaps one example for each operating system. file:///C:/Users/MY_USER/Desktop/p3/Institui%C3%A7%C3%A3o - is that the desired result, or do you want something else?

It sounds like you want to encode or decode the string, but into what encoding? Perhaps you want the encoding of the console that print() outputs to. That depends on the OS and terminal as well as the terminal’s settings. What are “non-utf-8” characters? Almost anything can be represented by UTF-8 (there are some exceptions, such as voiced Tamil script consonants, but that’s probably not what you are talking about). A character can have a different encoding such as UCS-2 (wide data in contrast to UTF-8 which is narrow), but it’s still a representation of the same character.

I added a complement to the question, maybe it will be easier to understand what I need

since python3.4 prefer pathlib instead os.path

Hallo

import uno
from pathlib import Path


def pathtest():
    doc = XSCRIPTCONTEXT.getDocument()

    url = doc.URL
    print(url)
    systempath = uno.fileUrlToSystemPath(url)
    print(systempath)
    p = Path(systempath)
    print(p)
    print(p.absolute())
    print(p.as_uri())
    print(p.parent)
    print( p.parent / "otherfilename" )

Excellent solution, that’s what I was looking for - (uno.fileUrlToSystemPath):

url = ODOC.URL
systempath = uno.fileUrlToSystemPath(url)

Many Thanks