I'm trying to replicate the ls function in bash with columns like this:

I tried .format to add padding to the file names but im still not getting the desired output the last column overflows everytime.
def show_dirs():
filelist = os.listdir(os.getcwd())
filelist.sort()
scr_width = int(os.popen("stty size", "r").read().split()[1])
max_len = -1
for file_len in filelist:
if len(file_len) > max_len and scr_width > max_len*2:
max_len = len(file_len)
mlen = max_len #+ 1
print(color["cyan"] + "Files in the current directory")
if scr_width < mlen:
mlen = scr_width
line = ""
for count, _file in enumerate(filelist):
if os.path.isdir(_file):
_file = _file + os.sep
st = "[{0:>2}] {1:<{mlen}}".format(str(count + 1), _file, mlen=mlen)
if len(line) % scr_width > len(st):
line = line + color["green"] + st
else:
line = line + "\n" + color["green"] + st
else:
st = "[{0:>2}] {1:<{mlen}}".format(str(count + 1), _file, mlen=mlen)
if len(line) % scr_width > len(st):
line = line + color["cyan"] + st
else:
line = line + "\n" + color["cyan"] + st
print(line)
I get this output:


Ncolumns, but would inN+1.