Warum ist nicht os.walk meine Variablennamen zu erkennen?
-
10-10-2019 - |
Frage
Ich habe folgende in TextWrangler geschrieben:
directory = raw_input("See contents of: ")
for root, dirs, files in os.walk(directory):
print root, dirs, files
Leider, wenn ich es im Terminal laufen und den Verzeichnispfad zuweisen, indem Sie oder einen Ordner in Schleppen aus dem Dock nichts passiert. Nicht einmal eine Fehlermeldung. Auf der anderen Seite, wenn ich folgende in TextWrangler gibt Sie dann das Programm im Terminal laufen, es funktioniert gut.
for root, dirs, files in os.walk("/Users/paulpatterson/Documents/Python"):
print root, dirs, files
Meine Frage ist dann, warum ist os.walk keinen Pfad in Form einer Variablen zu akzeptieren. Das Buch dass ich mit suggeriert sollte es, wie die meisten Beispiele habe ich im Netz gesehen habe während versuchen, diese zu sortieren.
Lösung
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:
- special chars like spaces get escaped for usage in the shell
- 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.
Andere Tipps
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