user3494047
user3494047

Reputation: 1693

Python path string adds an extra slash except for the last one

I have a path to a directory where I want to iterate over all of the files. It looks like this myPath = "D:\workspace\test\main\test docs" and when I print out myPath it looks like "D:\\workspace\test\\main\test docs" . As you can see it added a slash to every slash except the last one.

When I do for path, dirs, files in os.walk(myPath): it doesn't work if there isn' t the extra slash. Why isn't python adding the extra slash to the last slash?

It was working on a different computer.

Upvotes: 2

Views: 2032

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477676

Because '\t' is an escape sequence that makes sense: it is a tab, like is specified in the 2.4.1 String literals section. The others only happen not to make sense here, so Python will escape these for you (for free).

You can thus add the extra backslash like:

myPath = "D:\\workspace\\test\\main\\test docs"

or you can use a raw string, by prefixing it with r:

myPath = r"D:\workspace\test\main\test docs"

In that case:

Unless an r' orR' prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C.

So that means the backslash (\) is not interpreted as something special, but only as a backslash.

Upvotes: 3

Related Questions