开发者

Slicing of python os.listdir()

Can I make a slicing in os.listdir()? To take only a 开发者_如何学编程number of elements.


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']


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜