-1

我正在尝试将 '\' 与文件夹中的路径和文件名连接,但是当我尝试连接时,我在扫描字符串文字时遇到了 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

2 回答 2

2

使用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])
于 2016-10-22T20:38:49.743 回答
-1

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

 add = '\\'

根据字符串文字:转义字符文档,以下是所有转义序列及其含义的列表:

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)
于 2016-10-22T20:37:46.020 回答