PEP ? os.listdir enhancement

Riccardo Galli riccardo_cut1 at cut2_sideralis.net
Wed Jun 22 11:57:14 EDT 2005


Hi,
I noticed that when I use os.listdir I need to work with absolute paths
90% of times.
While I can use a for cycle, I'd prefere to use a list comprehension,
 but it becomes too long.

I propose to add an 'abs' keyword which would make os.listdir return the
absolute path of files instead of a relative path.
This would bring only advantages, I think.

I show two examples

from os import listdir
from os.path import isdir,join,getsize,isfile

### e.g. 1 part 1 - getting a list of directories ### 
dirs=[]
for i in os.listdir(path):
    tmp_path=os.path.join(path,i)
    if os.path.isdir(tmp_path):
        dirs.append(tmp_path)

### e.g. 1 part 2 ###
dirs=[join(path,x) for x in listdir(path) if isdir(join(path,x))]

here the list comprehension is still clear, but only because we have
direct references to join and friends. moreover whe need to use join twice
for each directory.

### e.g. 2 part 1 - getting a list of (file,size) tuples ### 
path_size=[]
for i in os.listdir(path):
    tmp_path=os.path.join(path,i)
    if os.path.isfile(tmp_path):
        path_size.append((tmp_path,getsize(tmp_path))

### e.g. 2 part 2 ###
dirs=[(join(path,x),getsize(join(path,x)) for x in listdir(path) if
    isfile(join(path,x))]


now list comprehension is way too long, and in the worst case we must use
join 3 times for each iteration.

adding an 'abs' keyword to os.listdir would give benefits both to for
cycle and list comprehensions.
for cycle would lose the tmp_path assignment and list comprehensions ...


### e.g. 1 part 2 bis ###
dirs=[x for x in listdir(path,abs=True) if isdir(x)]

here we gain clearness and speed.

### e.g. 2 part 2 bis ### 
dirs=[(x,getsize(x)) for x in listdir(path,abs=True) if isfile(x)]

and here we gain clearness, speed and a truely _usable_ list comprehension

What do you think about this ?

Thanks for reading,
Riccardo

-- 
Riccardo Galli
Sideralis Programs
http://www.sideralis.net



More information about the Python-list mailing list