0

I'm looking to create two columns with os.listdir. Code is standard listdir().

for f in os.listdir(os.curdir):
                print f

Output looks like as follows:

file1
file2
file3
file4

But I'm trying to achieve:

file1    file3
file2    file4

Is that (easily) achievable with os.listdir()?

4 Answers4

2

os.listdir just returns a list, doesn't print it nicely like ls -C2 would do (note that you don't need python for that if you have ls in your system)

You could do it this way for 2 colums:

import os,itertools

dl=os.listdir(".")

for t in itertools.zip_longest(dl[::2],dl[1::2],fillvalue=""):
    print("{:<20} {:<20}".format(*t))

that would interleave the values together (with zip_longest to avoid forgetting an odd one) and format using 20 spaces for each value.

The general case for any number of columns could be:

import os,itertools

dl=os.listdir(".")

ncols = 3

for t in itertools.zip_longest(*(dl[i::ncols] for i in range(ncols)),fillvalue=""):
    print(("{:<20}"*ncols).format(*t))

(generating ncols shifted lists, interleaving them, and generating the format accordingly)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

No, it is not possible with os.listdir(). You may have to conside other options like How to print a list more nicely?.

xystum
  • 939
  • 6
  • 8
0

You can do it easily using function pairwise from this anwser

def pairwise(iterable):
    a = iter(iterable)
    return izip(a, a)

for f1, f2 in pairwise(os.listdir(os.curdir)):
    print f1 + '\t' + f2
M. Galczynski
  • 634
  • 1
  • 5
  • 12
0

Try this,

for i,k in zip(os.listdir(os.curdir)[0::2], os.listdir(os.curdir)[1::2]): print i,k
Muthuraj S
  • 107
  • 6