字符串连接“\”蟒蛇

问题描述:

我试图串连“\”的路径和文件夹中的文件名,但是当我尝试来连接,我收到EOL同时扫描字符串文字:字符串连接“”蟒蛇

path = r"C:\Users\karth\Desktop\udacity\2000" 
add = '\' 
file = os.listdir(path) 
['2000Q1.zip', 
'2000Q2.zip', 
'2000Q3.zip', 
'2000Q4.zip', 
'Acquisition', 
'Performance'] 

print (path+ add + file[0]) 
+4

只要看看突出显示 - 您正在用'\''转义引号。 – Li357

+2

为什么你使用原始符号作为'path'而不是'add'? – Goyo

+3

'os.path.join'函数可以正确处理这个问题 – agg3l

当您在字符串中使用\'时,它会将'作为字符串的一部分(而不是字尾引号)。 \被称为转义字符。你需要把它写成:

add = '\\' 

String Literals: Escape Characters文件,下面是所有转义序列与它们的含义的列表:

Escape Sequence  Meaning 
\newline   Ignored 
\\     Backslash (\) 
\'     Single quote (') # <---- Cause of error in your code 
\"     Double quote (") 
\a     ASCII Bell (BEL) 
\b     ASCII Backspace (BS) 
\f     ASCII Formfeed (FF) 
\n     ASCII Linefeed (LF) 
\r     ASCII Carriage Return (CR) 
\t     ASCII Horizontal Tab (TAB) 
\v     ASCII Vertical Tab (VT) 
\uxxxx    Character with 16-bit hex value XXXX (Unicode only (1) 
\Uxxxxxxxx   Character with 32-bit hex value XXXXXXXX (Unicode only) (2) 
\v     ASCII Vertical Tab (VT) 
\ooo    Character with octal value OOO (3,5) 
\xhh    Character with hex value HH (4,5) 
+0

它适用于我的情况谢谢 –

使用os.path.join

path = r"C:\Users\karth\Desktop\udacity\2000" 
file = os.listdir(path) 

print(os.path.join(path, file[0])) 

glob.glob以整个路径列出目录:

import glob 
pattern = r"C:\Users\karth\Desktop\udacity\2000\*" 
filenames = glob.glob(pattern) 
print(filenames[0]) 
+0

谢谢你的工作完美 –

+0

为了使这更好,解释为什么OP代码没有先工作,然后提供解决方案:) – Li357