earnestt1234/seedir

[FR] itemlimit only for files but not folders.

Closed this issue · 4 comments

I wish to show only 2 first files of all folders/subfolders.

Currently, itemlimit can limit folders, I wish to only limit files, but continue to scan all subfolders.

Also is there any way to save the output in a file.txt instead of just print it ?

Interesting suggestion! I could see having folderlimit/filelimit arguments which do what you request. I'll have a look into how to add that.

In the meantime, here is a workaround. You can overwrite the function for listing the children of a directory, such that you only return at most two files (and all folders). Something like so:

import os

import seedir as sd
from seedir.folderstructure import RealDirStructure

def twofile_listdir(path):

    limit_files = 2

    output = []
    file_count = 0

    for entry in os.listdir(path):
        fullpath = os.path.join(path, entry)
        if os.path.isfile(fullpath) and file_count < limit_files:
            output.append(fullpath)
            file_count += 1
        elif os.path.isdir(fullpath):
            output.append(fullpath)

    return output

RealDirStructure.listdir = twofile_listdir

The last line is redefining the default behavior for listing folder contents. So when I call sd.seedir() on any path, it should use twofile_listdir. For example, this directory:

>>> sd.seedir(path)
test/
├─Hardin.txt
├─Kathleen.txt
└─arabesque/
  ├─compulsion.txt
  ├─wapiti.txt
  └─introductory/
    ├─expectant.txt
    ├─amicable.txt
    └─indifferent/

But the full folder looks like so (generated with sd.randomdir(seed=7, files=5, folders=1, stopchance=0, name='test')):

test/
├─Hardin.txt
├─Kathleen.txt
├─berserk.txt
├─Indochina.txt
├─ouvre.txt
└─arabesque/
  ├─deify.txt
  ├─Jones.txt
  ├─wapiti.txt
  ├─compulsion.txt
  ├─Cushman.txt
  └─introductory/
    ├─expectant.txt
    ├─sustain.txt
    ├─paratroop.txt
    ├─faculty.txt
    ├─amicable.txt
    └─indifferent/

And for saving to text, there is nothing implemented in seedir specific for this - though it is not hard to do with base Python:

import seedir as sd

# return string instead of print
s = sd.seedir(path, printout=False)

# write
with open('file.txt', 'w') as f:
    f.write(s)

OP's (@softyoda) original feature request has been added as part of v0.5.0. Relevant changes are in 644b909 and e383d85.

Rather than adding more arguments, the itemlimit argument can now acceptable a 2-tuple of integers. The first number specifies the limit for folders, and the second number specifies the limit for files. None can still be used to specify no limit for one or the other. So to only show 2 files and all folders (OP's example):

import seedir as sd
sd.seedir('path', itemlimit=(None, 2))