[英]Extracting files from subfolders
I have this code below extract just the first file from each subfolder.我在下面有这段代码,仅从每个子文件夹中提取第一个文件。 How do I modify to get say the first 100 files?
如何修改以获取前 100 个文件?
import os
result_files = []
for root, dirs, files in os.walk(your_folder):
if files:
result_files.append(sorted(files)[0])
You can slice the first 100 values from the sorted list of files and then extend.您可以从已排序的文件列表中分割前 100 个值,然后进行扩展。
result_files.extend(sorted(files)[:100])
Replace the line you had with this用这个替换你的行
result_files.extend(sorted(files)[:100])
Or, since files
is a list, we can also do:或者,由于
files
是一个列表,我们也可以这样做:
result_files += sorted(files)[:100]
Both of these work because of a pythonic feature called list slicing.这两项工作都是因为一个称为列表切片的 Python 特性。 You can read more about it here and here .
您可以在此处和此处阅读有关它的更多信息。
Another option is this one:另一种选择是这个:
for i in range(100): result_files.append(sorted(files)[i])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.