0

Can I make a slicing in os.listdir()? To take only a number of elements.

stdio
  • 435
  • 2
  • 7
  • 18
  • Sorry, I'm beginning with python. I didn't think It was possible to use "[:]" out of a function like g.d.d.c user did. – stdio Jun 07 '11 at 19:51
  • 1
    In Python you can chain operations as long as it makes sense based on the preceding return type. In this case, `os.listdir()` returns a list, which makes slice notation on it valid. If it returned a generator instead you'd need to convert it to a list somehow in order to be able to slice it. – g.d.d.c Jun 07 '11 at 19:54
  • @g.d.d.c: I've strong bases of the C language and it's not easy at first to get a view of python's reasoning. thanks – stdio Jun 07 '11 at 20:00
  • 1
    Even if not, you could just store the result somewhere and then slice that. –  Jun 07 '11 at 20:06

2 Answers2

3

I don't see why not:

>>> os.listdir(os.getcwd())
['CVS', 'library.bin', 'man', 'PyLpr-0.2a.zip', 'pylpr.exe', 'python26.dll', 'text']
>>> os.listdir(os.getcwd())[3:]
['PyLpr-0.2a.zip', 'pylpr.exe', 'python26.dll', 'text']
g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
3

Since os.listdir(path) returns a list, you can use slice notation on the result. For example, you can use os.listdir(path)[:5] to get the first 5 results:

>>> import os
>>> os.listdir('.')
['f1', 'f10', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9']
>>> os.listdir('.')[:5]
['f1', 'f10', 'f2', 'f3', 'f4']

See Explain Python's slice notation for a comprehensive overview of slice notation.

Community
  • 1
  • 1
Gregg
  • 3,236
  • 20
  • 15