Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. import os
  2. import logging
  3.  
  4. def create_structure(target_dir, structure):
  5. if '~' in target_dir:
  6. target_dir = target_dir.split('~')
  7.  
  8. # Join without os.path.join due to possiblity of absolute path
  9. target_dir = os.path.expanduser('~') + target_dir[1]
  10.  
  11. for item in structure:
  12. itype = item['type']
  13. fname = item['name']
  14. sub = item.get('sub', False)
  15.  
  16. path = os.path.join(target_dir, fname)
  17.  
  18. if itype == 'folder':
  19. if not os.path.isdir(path):
  20. os.makedirs(path)
  21.  
  22. if sub:
  23. create_structure(path, sub)
  24.  
  25. elif itype == 'file':
  26. content = item.get('content', False)
  27.  
  28. with open(path, 'w+') as f:
  29. if content:
  30. f.write(content)
  31.  
  32. else:
  33. logging.warn('Invalid type: [{}]'.format(itype))
  34.  
  35.  
  36.  
  37.  
  38.  
  39. if __name__ == "__main__":
  40. create_structure('~/Desktop', [
  41. {
  42. "type": "folder",
  43. "name": "scripts",
  44. "sub": [
  45. {
  46. "type": "file",
  47. "name": "history.json"
  48. }
  49. ]
  50. },
  51. {
  52. "type": "folder",
  53. "name": "repos"
  54. },
  55. {
  56. "type": "file",
  57. "name": "history.json",
  58. "content": '''
  59. {
  60. 'name': 'test'
  61. }
  62. '''
  63. }
  64. ]
  65. )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement