Advertisement
Guest User

Untitled

a guest
Sep 19th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. """
  2. * Listing files in directories and subdirectories
  3. * inspired by an example by Daniel Shiffman.
  4. *
  5. * 1) List the names of files in a directory
  6. * 2) List the names along with metadata (size, lastModified)
  7. * of files in a directory
  8. * 3) List the names along with metadata (size, lastModified)
  9. * of files in a directory and all subdirectories (using recursion)
  10. """
  11.  
  12. from datetime import datetime
  13. import os
  14.  
  15. def sizeof_fmt(num):
  16. for fmt in ['%3d bytes', '%3dK', '%3.1fM', '%3.1fG']:
  17. if num < 1024.0:
  18. return fmt % num
  19. num /= 1024.0
  20.  
  21. def print_file_details(f, depth=0):
  22. if os.path.basename(f)[0] == '.':
  23. return # no dotfiles
  24. print ' ' * depth, # funny Python syntax: trailing comma means no newline
  25. if os.path.isdir(f):
  26. print "+%s" % os.path.basename(f)
  27. else:
  28. mtime = datetime.fromtimestamp(os.path.getmtime(f))
  29. info = '%s, modified %s' % (sizeof_fmt(os.path.getsize(f)),
  30. mtime.strftime("%Y-%m-%d %H:%M:%S"))
  31. print "%-30s %s" % (os.path.basename(f), info)
  32.  
  33. def list_recursively(f, depth=0):
  34. if os.path.basename(f)[0] == '.':
  35. return # no dotfiles
  36. print_file_details(f, depth)
  37. if os.path.isdir(f):
  38. for g in os.listdir(f):
  39. path = os.path.join(f, g)
  40. list_recursively(path, depth + 1)
  41.  
  42. topdir = os.getcwd()
  43.  
  44. print "Listing names of all files in %s:" % topdir
  45. for f in os.listdir(topdir):
  46. print f
  47.  
  48. print "Listing info about all files in %s:" % topdir
  49. for f in os.listdir(topdir):
  50. print_file_details(f)
  51.  
  52. print "---------------------------------------"
  53. print "Descending into %s:" % topdir
  54. list_recursively(topdir)
  55.  
  56. exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement