连接路径和文件名 [英] Concatenate path and filename

查看:148
本文介绍了连接路径和文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在python中一起构建完整路径.我试过了:

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])

但是我得到这个错误

SyntaxError:扫描字符串文字时会停工.

SyntaxError: EOL while scanning string literal.

推荐答案

反斜杠字符(\)必须在字符串文字中转义.

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

  • 这是错误的:'\'
  • 这是正确的:'\\'-这是一个包含一个反斜杠的字符串
  • This is wrong: '\'
  • This is correct: '\\' - this is a string containing one backslash

因此,这是错误的:

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

有个窍门!

r为前缀的字符串文字旨在简化正则表达式的编写.它们的功能之一是不必转义反斜杠字符.这样就可以了:

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'\'-这是语法错误
  • r'\' - this is a syntax error

所以,这也是错误的:

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])

这篇关于连接路径和文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆