Python Query
Oliver Schaefer
SchaeferFFM at hotmail.com
Tue Mar 7 16:03:32 EST 2000
ns56645 wrote:
> Hi,
> Can anybody give me a code for the following in python:
> Program which does directory listing and everything that is a directory,
> the program puts the word "Directory" in front of it.
> The output should be as follows:
> a1.txt
> r1.bat
> k1 Directory
> a2.txt
> r2.txt
> k2 Directory
> because k1 and k2 are directories
> Thanking you in anticipation
> Shah
>>> help(listdir)
(dirname='.', columns=40, truncate=0)
sorted directory listing.
dirname may be relative
columns [=40] - min length of filenames
truncate [=0] - max length of filenames
0 means don't truncate
>>> print listdir('/')
.bash_history
.bash_profile
.bashrc
AUTOEXEC.BAT
COMMAND.COM
CONFIG.SYS
Eigene Dateien directory
IO.SYS
Inetpub directory
MSDOS.SYS
Multimedia Files directory
Programme directory
RECYCLED directory
Windows directory
html directory
jdk directory
jre directory
>>> print listdir('/', 10, 10)
.bash_hist
.bash_prof
.bashrc
[...]
Eigene Dat directory
[...]
[listdir]----------------------------------------
def listdir(dirname='.', columns=40, truncate=0):
"""\
sorted directory listing.
dirname may be relative
columns [=40] - min length of filenames
truncate [=0] - max length of filenames
0 means don't truncate
"""
import os, string
dirname = os.path.abspath(dirname)
dirlist = os.listdir(dirname)
dirlist.sort()
res = []
isdir = os.path.isdir
join = os.path.join
if truncate:
# %% --> escape %
# %-m.Ps --> left justification, m columns minimum length
# P columns precision (maximum length)
format = '%%-%d.%ds %%s' % (columns, truncate)
else:
format = '%%-%ds %%s' % columns
for filename in dirlist:
fullname = join(dirname, filename)
if isdir(fullname):
typ = 'directory'
else:
# you may want to display the file size with
# typ = '%9d' % os.path.getsize(fullname)
# (right justification, 9 digits min length)
typ = ''
res.append(format % (filename, typ))
return string.join(res, '\n')
[/listdir]----------------------------------------
Regards,
Oliver Schaefer [ SchaeferFFM at gmx.de ]
using stackless ...
More information about the Python-list
mailing list