读取文件系统中排序的文件 [英] Reading files as sorted in my file system

查看:114
本文介绍了读取文件系统中排序的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历我拥有的文件,并希望将每两个文件成对放置,尤其是彼此紧随其后的每两个文件实际上是相关的.

I'm trying to loop through files I have, and would like to put every two files in a pair, especially that every two files coming after each other are actually related.

我在目录中对文件进行了排序,并使用以下内容遍历目录并读取文件对:

I have the files sorted in my directory, and I used the following to loop through the directory and read the pairs of files:

for root, dirs, files in os.walk(TRAIN_DIR):
        for file1, file2 in itertools.izip_longest(files[::2], files[1::2]):

但是,我收到文件1和文件2的顺序不同,而不是目录中应该紧接的两个文件. os.walk是否会返回未排序的文件?为了按顺序浏览文件,我该怎么办?

However, I receive file1 and file2 in different orders, and not those two files that should come immediately after each other as in the directory. Does os.walk then return unsorted files? What should I do in order to walk through the files in a sorted order?

这是我的前四个文件在系统中的列出方式:

This is how my first four files are listed in my system:

0a1a465c-a28d-4926-8a79-81ba83408c52.1.a
0a1a465c-a28d-4926-8a79-81ba83408c52.2.a
0a1b8b67-6c03-47c6-9af9-0e0091148e06.1.a
0a1b8b67-6c03-47c6-9af9-0e0091148e06.2.a

我如何按顺序阅读它们?

How can I read them in that order?

谢谢.

推荐答案

如此处 os .walk按什么顺序进行迭代?编写后,您可以在第二个循环之前添加sort()方法:

as here os.walk iterates in what order? written you can add the sort() method before the second loop:

for root, dirs, files in os.walk(TRAIN_DIR):
    files.sort()
    for file1, file2 in itertools.izip_longest(files[::2], files[1::2]):

这篇关于读取文件系统中排序的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆