stupid question about os.listdir
Jason Kratz
eat at joes.com
Thu Jun 26 23:47:43 EDT 2003
Peter Hansen wrote:
> Jason Kratz wrote:
>
>>def getdirs(path):
>> os.chdir(path)
>> for entry in os.listdir(path):
>> if os.path.isdir(entry):
>> dirs.append(entry)
>>
>>if I run this from the command line on linux with 'python backup.py' it
>>works *if* I have os.chdir in there. if I comment it out it doesnt list
>>starting from the root dir...it starts in my home dir.
>
>
> This might mean you are not passing it an absolute path, but
> instead a relative one. Absolute paths (on Linux) are those
> which start with a / (forward slash). Anything without that
> will start from the current directory only.
>
> But without actual examples of which paths are failing, as
> Ben has asked for, we know nothing for certain.
>
> Is it also possible that you are not having a problem with listdir()
> at all, but with the values you are passing to os.path.isdir()?
> You realize that os.listdir() returns names that are *relative*
> to the path parameter you give it? So that if you then pass those
> to isdir() you will get nothing useful if you don't first do
> this instead? :
>
> entry = os.path.join(path, entry)
> if os.path.isdir(entry):
> dirs.append(entry)
>
> -Peter
Peter-
Thanks much for the reply. You are completely correct and I managed to
work thru it myself (just finished right before I read your posting) and
I actually had the exact code (aside from using a new var instead of
reusing entry) you have just above (with the join). Was going to post
it and find out if that was the "correct" way of doing it ;)
This is my code:
import os
import os.path
def getdirs(path):
dirs=[]
for entry in os.listdir(path):
fullpath=os.path.join(path,entry)
if os.path.isdir(fullpath):
dirs.append(fullpath)
return dirs
print getdirs('/')
More information about the Python-list
mailing list