今天在引用路径的时候出现了这个问题: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')