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()?
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)