Advertisement
Guest User

Untitled

a guest
Jan 24th, 2017
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. import os
  2. from collections import defaultdict
  3.  
  4.  
  5. def get_files(dir_name):
  6. """Gets all the files from the specified directory
  7.  
  8. Starting from the specified directory, gathers all the files in the
  9. defaultdict (dictionary-like object), list of files of particular type
  10. can be pulled out using ".extension" key on the resulting dictionary.
  11.  
  12. files = get_files(my_directory)
  13. txt_files = files[".txt"]
  14. exe_files = files[".exe"]
  15.  
  16. Input value dir_name can be either a name of a directory placed in the
  17. current working directory (os.getcwd()) or it's full path.
  18. """
  19.  
  20. if os.path.exists(dir_name) and os.path.isdir(dir_name):
  21. dirs = [dir_name]
  22. files = defaultdict(list)
  23. while dirs:
  24. current_dir = dirs.pop()
  25. for f in os.listdir(current_dir):
  26. if os.path.isdir(os.path.join(current_dir, f)):
  27. dirs.append(os.path.join(current_dir, f))
  28. else:
  29. ext = os.path.splitext(f)[1]
  30. files[ext].append(f)
  31. return files
  32. raise NotADirectoryError(
  33. "Given directory name doesn't refer to a valid directory."
  34. )
  35.  
  36.  
  37. def print_file(files, extension):
  38. """Takes a list of files and their extension, prints in nice format."""
  39. if files:
  40. print("{} files:\n".format(extension))
  41. print("\n".join("- {}".format(f) for f in files))
  42. print("\n")
  43. else:
  44. print("no files of type {} found\n".format(extension))
  45.  
  46.  
  47. def print_files(mapping, extensions=None):
  48. """Prints files of specified extensions (all by default).
  49.  
  50. Prints the files of specified extensions (all by default) based on
  51. the mapping received from the get_files function.
  52. """
  53. if extensions is not None:
  54. for ext in extensions:
  55. print_file(mapping["." + ext], ext)
  56. else:
  57. for ext in mapping:
  58. print_file(mapping[ext], ext.lstrip('.'))
  59.  
  60.  
  61. def main():
  62. import argparse
  63. parser = argparse.ArgumentParser(description="get files from a directory")
  64. parser.add_argument('dir_name', help="name of a directory (or full path)")
  65. parser.add_argument('-t', help="file type(s) to output", nargs='+',
  66. dest='extensions', metavar='ext')
  67. args = parser.parse_args()
  68. try:
  69. mapping = get_files(args.dir_name)
  70. print('\n')
  71. print_files(mapping, args.extensions)
  72. except NotADirectoryError as e:
  73. print(e)
  74.  
  75.  
  76. if __name__ == '__main__':
  77. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement