os.walk analogue in PyQt

戏子无情 提交于 2019-12-01 22:36:48

Should I use os.walk or something much faster and more informative?

There is none, and I would recommend using os.walk in python if you can. It is just as good as it gets.

It is not only because Qt does not have such a convenience method, but even if you write your own mechanism based on QDir, you will have access to all the three variables without hand-crafting like with os.walk.

If you are desperate about using Qt, then you could have the following traverse function below I used myself a while ago.

main.cpp

#include <QDir>
#include <QFileInfoList>
#include <QDebug>

void traverse( const QString& dirname )
{
    QDir dir(dirname);
    dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoSymLinks | QDir::NoDot | QDir::NoDotDot);

    foreach (QFileInfo fileInfo, dir.entryInfoList()) {
      if (fileInfo.isDir() && fileInfo.isReadable())
          traverse(fileInfo.absoluteFilePath());
      else
          qDebug() << fileInfo.absoluteFilePath();
    }
}

int main()
{
    traverse("/usr/lib");
    return 0;
}

or simply the following forfor large directories and in general since it scales better and more convenient:

#include <QDirIterator>
#include <QDebug>

int main()
{
    QDirIterator it("/etc", QDirIterator::Subdirectories);
    while (it.hasNext())
        qDebug() << it.next();
    return 0;
}

main.pro

TEMPLATE = app
TARGET = qdir-traverse
QT = core
SOURCES += main.cpp

Build and Run

qmake && make && ./qdir-traverse

Then, you will get all the traversed files printed. You can start customizing it then further to your needs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!