Search code examples
bashpython-3.xdirectorypyqt5

How to read n files from directory in Python?


I'm doing a PyQT5 application that needs to select the given folder, and list all the files and directories in it.

To fetch the path, I use simple method that looks like:

def open_path():
    dialog = QFileDialog()
    folder_path = dialog.getExistingDirectory(None, "Select Folder")
    return folder_path

EDIT

This is how I fetch the roots, dirs, and files

import os

# this is where I have my open_path() method defined, so I don't write it again

path = str(open_path())
roots = next(os.walkpath(path))[0]
dirs = next(os.walkpath(path))[1]
files = next(os.walkpath(path))[2]

I have a folder that contains around 11000 files. I use QFileDialog to fetch the folder, and split it into the 3 lists (roots, dirs, files), and use QDir to display it.

Because of its size, I want to limit the QDir display only first 1000 files, with possibility to load more, after reaching 1000.

Is this possible to do and how?

I couldn't find any documentation or example on how to implement this kind of filter.

I was searching for this info everywhere on the web, but only found this solution -> How to read first n-th files from directory (pleaso NOT a "head -n solution")? which involves the bash scripting?

I want to avoid using Popen, and PIPE if possible.

Any help or tip is welcome.

Thank you.


Solution

  •   parent_list = os.listdir("Here goes the path for directory")
      count =0
      for child in parent_list:
       if count < 1000:
          print(child)
       else
           break
       count = count+1
    

    Here parent_list contains all the file in the given directory, and you can access the first 1000 files in the list using loop. child is the file in the directory