【python】字符串缺少结尾引号报错问题||路径字符串问题

问题描述

【python】字符串缺少结尾引号报错问题||路径字符串问题_第1张图片
今天在引用路径的时候出现了这个问题:Missing closing quote[’]
我写的路径字符串是:r'D:\projects\PYTHON\thesis\clients_in_same_type\' + usage_type +'.xlsx'
看起来没有什么问题,是'D:\projects\PYTHON\thesis\clients_in_same_type\'usage_type'xlsx'三个字符串的拼接,但是实际上这里有个问题:python中的字符串不能以backslash(\)结尾,例如:

a_really_really_really_really_really_really_really_long_list.append('a_really_really_' \
                                                                     'really_really_really_long_string')

问题原因

python的字符串不能以backslash结尾,因为 \ 这个符号在python中转行连接的含义,也就是如果一行代码太长,可以使用backslash将一行代码转成两个。所以字符串不可以以这个符号结尾。
所以最后我上面的cur_filename实际上会被翻译成字符串:'D:\projects\PYTHON\thesis\clients_in_same_type\' + usage_type +'和一个不是字符串的东西:.xlsx'

同时,python在字符串中会 自动将backslash后面的字符算入字符串内容中。所以在python看来clients_in_same_type\后面的那个不算是字符串的引号,而是这个字符串本身的一部分


解决方式

可以使用os.path.join这个方法:

        cur_filename = os.path.join(r'D:\projects\PYTHON\thesis\clients_in_same_type', usage_type, '.xlsx')

你可能感兴趣的:(python)