Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 763
nina_berlini Avatar asked Nov 14 '16 19:11

nina_berlini


2 Answers

Try:

import os
os.path.join('C:\Users\A\Desktop\Repo', filename)

The os module contains many useful methods for directory and path manipulation

like image 175
zanseb Avatar answered Oct 17 '22 06:10

zanseb


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])
like image 28
zvone Avatar answered Oct 17 '22 05:10

zvone