-2

I'm trying to get os.walk() to work in a program I'm working on, but I keep getting the error: ValueError: invalid \x escape

From looking around online, I've seen that the error can arise from not using a raw string. However, I still keep getting the error...

import os
path = r'D:\Data\Tracking\'

for root, dirs, files in os.walk(path):
    print root
    print dirs
    print files

Anyone have an idea of what I can do differently to make it work?

Schack
  • 833
  • 2
  • 7
  • 18
  • 2
    Can you post the complete error message and full traceback? – BrenBarn May 02 '13 at 19:51
  • I believe that the backslash still escapes quotes in a string, so drop the last backslash. See also the syntax highlighting here, which highlights this mistake. Where the exact error comes from is probably in the part of the code not shown. – Ulrich Eckhardt May 02 '13 at 19:53
  • 1
    `path = r'D:\Data\Tracking'`. ``\'`` is the root of evil – gongzhitaao May 02 '13 at 19:55
  • 2
    Why don't you simply use forward slashes? – stranac May 02 '13 at 19:56
  • 1
    possible duplicate of [Python raw strings and trailing backslash](http://stackoverflow.com/questions/2870730/python-raw-strings-and-trailing-backslash) – mgilson May 02 '13 at 20:01
  • So, I was commenting out a large section of my code using '''. I guess that is bad, because python recognizes the triple quotes as doc tools. I thought the triple quote commented everything out. Thanks everyone for your help. – Schack May 02 '13 at 20:12

2 Answers2

1

I'm a little surprised that you're getting a ValueError... but notice that the problem is with the trailing '.

>>> path = r'D:\Data\Tracking'
>>> path = r'D:\Data\Tracking\'
  File "<stdin>", line 1
    path = r'D:\Data\Tracking\'
                              ^
SyntaxError: EOL while scanning string literal

For workarounds, see Why can't a raw string end in an odd number of trailing backslashes

My favorite is:

>>> path = r'D:\Data\Tracking' '\\'

which uses automagic string concatenation of literals.

mgilson
  • 300,191
  • 65
  • 633
  • 696
1

Try using \\ to prevent the last backslash from escaping the quote after it.

>>> path = r'D:\Data\Tracking\'
  File "<input>", line 1
    path = r'D:\Data\Tracking\'
                              ^
SyntaxError: EOL while scanning string literal
>>> path = r'D:\Data\Tracking\\'
>>> print(path)
D:\Data\Tracking\\

You can do this without a raw string to get the exact string that you want:

>>> path = 'D:\\Data\Tracking\\'
>>> print(path)
D:\Data\Tracking\
Nolen Royalty
  • 18,415
  • 4
  • 40
  • 50