joce
joce

Reputation: 9902

os.walk doesn't walk

While fiddling around to try to automate some process, I ran into this seemingly very strange behavior of Python's os.walk(): when I pass it some directory, it just doesn't do anything. However, when I pass the parent directory, it recurses properly in the path that doesn't seem to work when passed directly.

For example:

for root, _, _ in os.walk('F:\music'):
    print(root)

produces the following output:

F:\music
[...]
F:\music\test
F:\music\test\broken
F:\music\test\broken\Boards_Of_Canada
F:\music\test\broken\Brian_Eno
[...]

But when I try with F:\music\test (which was recursed in just fine when os.walk() was called on its parent) as such:

for root, _, _ in os.walk('F:\music\test'):
    print(root)

I don't get any output at all.

Does anybody have an idea what's going on? Am I doing something wrong? Is it some weird limitation of os.walk()? I'm really confused.

Upvotes: 6

Views: 14165

Answers (4)

HSMKU
HSMKU

Reputation: 356

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

Windows Path Work with "\\" !

Upvotes: 0

dmitry voronin
dmitry voronin

Reputation: 41

you better use os.path.normpath and use any slashes and backslashes (in any amount) you like it will not only help with your issue but also will make your code cross platform at this point

for root, _, _ in os.walk(os.path.normpath('F:/music/test')):

Upvotes: 2

bgporter
bgporter

Reputation: 36574

Your problem is here:

 for root, _, _ in os.walk('F:\music\test'):
     print(root)

...when Python parses the string containing your path, it interprets the \t as a Tab character. You can either rewrite your path string literal as 'f:\\music\\test' or as r'F:\music\test' (a raw string, which exists for exactly this reason.)

Upvotes: 23

Tyler Eaves
Tyler Eaves

Reputation: 13133

You should always use forward slashes not back slashes in paths, even on windows. What's happening is that \t is being interpreted as a tab, not slash-tee.

Upvotes: 7

Related Questions