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.
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.)
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.
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')):
for root, dirs, files in os.walk("\\"): print(root) print(dirs) print(files)
Windows Path Work with "\\" !
精彩评论