python os.listdir() 的切片

0 投票
2 回答
1954 浏览
提问于 2025-04-16 19:07

我可以在os.listdir()中进行切片吗?只取其中的一部分元素。

2 个回答

3

因为 os.listdir(path) 会返回一个列表,所以你可以对这个结果使用切片的方式。比如,你可以用 os.listdir(path)[:5] 来获取前5个结果:

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

想了解切片的用法,可以查看 这篇关于Python切片的详细介绍

3

我不明白为什么不可以:

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

撰写回答