Search code examples
pythonpathfilepath

Concatenate path and filename


I have to build the full path together in python. I tried this:

filename= "myfile.odt"

subprocess.call(['C:\Program Files (x86)\LibreOffice 5\program\soffice.exe',
                    '--headless',
                    '--convert-to',
                    'pdf', '--outdir',
                    r'C:\Users\A\Desktop\Repo\',
                    r'C:\Users\A\Desktop\Repo\'+filename])

But I get this error

SyntaxError: EOL while scanning string literal.


Solution

  • Backslash character (\) has to be escaped in string literals.

    • This is wrong: '\'
    • This is correct: '\\' - this is a string containing one backslash

    Therefore, this is wrong:

    'C:\Program Files (x86)\LibreOffice 5\program\soffice.exe'
    

    There is a trick!

    String literals prefixed by r are meant for easier writing of regular expressions. One of their features is that backslash characters do not have to be escaped. So, this would be OK:

    r'C:\Program Files (x86)\LibreOffice 5\program\soffice.exe'
    

    However, that wont work for a string ending in backslash:

    • r'\' - this is a syntax error

    So, this is also wrong:

    r'C:\Users\A\Desktop\Repo\'
    

    So, I would do the following:

    import os
    import subprocess
    
    
    soffice = 'C:\\Program Files (x86)\\LibreOffice 5\\program\\soffice.exe'
    outdir = 'C:\\Users\\A\\Desktop\\Repo\\'
    full_path = os.path.join(outdir, filename)
    
    subprocess.call([soffice,
                     '--headless',
                     '--convert-to', 'pdf',
                     '--outdir', outdir,
                     full_path])