假设文件夹A包含以下文件:
0.jpg
1.jpg
2.jpg
.
.
.
n.jpg
.
.
.
现在,python 脚本查看文件夹 A 并使用
for path, dirs, files in os.walk(path_to_A):
for filename in files:
fullpath = os.path.join(path, filename)
读取 filename(读取每个图像)并更新数组 B。 数组B的大小恰好是A中图片的个数。
我的问题是,数组的第 j 个位置是否总是对应于 j.jpg 图像文件?
例如,如果文件夹 A 中的名称不同(但按字典顺序排序 - 顺便说一句,当我们在 win 或 linux 操作系统中列出目录时,它真的是保留的字典顺序吗?)这将在数组中描述乙?
谢谢!
请您参考如下方法:
不,第 j 个位置会(或至少可以)变化。来自 the docs (强调我的)
os.listdir(path='.')
Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory.
就是说,如果您希望它排序,sorted 会生成一个稳定的按字典顺序排序的列表。 sorted(os.listdir("your/path/here"))[n] 应该总是指向第 n 个文件(除非你的目录改变了内容!)
