开发者

Why isn't os.walk recognising my variable name?

I've written the following in TextWrangler:

directory = raw_input("See contents of: ") 

for root, dirs, files in os.walk(direct开发者_StackOverflow中文版ory):
   print root, dirs, files

Unfortunately, when I run it in terminal and assign the directory path by typing or dragging a folder in from the dock nothing happens. Not even an error message. On the other hand when I enter the following in TextWrangler then run the program in Terminal, it works fine.

for root, dirs, files in os.walk("/Users/paulpatterson/Documents/Python"):
print root, dirs, files

My question then, why is os.walk not accepting a path in the form of a variable. The book that I'm using suggests it should, as do most of the examples I've seen on the net whilst trying to sort this out.


Simply print directory before the loop to see what path you really get. That’s the problem, not that os.walk is not accepting variables.

When you drop a folder under OSX into the terminal:

  1. special chars like spaces get escaped for usage in the shell
  2. a space is inserted after the directory name

Both will prevent os.walk from finding the path. That you don't get an error is simple. os.walk doesn't give an error for that case. It simply doesn't iterate over the non-existing path.


Unfortunately, when I run it in terminal and assign the directory path by typing or dragging a folder in from the dock nothing happens.

I have tried this by, as you said, dragging the folder to my terminal (I am on Linux) and it displays the path surrounded with quotes.

Remove the quotes after your raw_input should fix your problem

import os

directory = raw_input("See contents of: ")
directory = directory.strip()
if directory[0] == "'" and directory[-1] == "'":
    directory = directory[1:-1]

print directory

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜