-1

I am trying to concatenate '\' with the path and the filename in the folder but when I try to concatenate, I'm getting EOL while scanning string literal:

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])
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
Karthik Elangovan
  • 133
  • 1
  • 2
  • 9

2 Answers2

2

Use os.path.join:

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

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

or glob.glob to list directories with the whole path:

import glob
pattern = r"C:\Users\karth\Desktop\udacity\2000\*"
filenames = glob.glob(pattern)
print(filenames[0])
Daniel
  • 42,087
  • 4
  • 55
  • 81
-1

When you use \' within the string, it takes ' as the part of string (and not the closing string quote). \ is know as escape character. You need to write it as:

 add = '\\'

As per String Literals: Escape Characters document, below is the list of all the Escape Sequences with their meanings:

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)
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126