Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import logging
- def create_structure(target_dir, structure):
- if '~' in target_dir:
- target_dir = target_dir.split('~')
- # Join without os.path.join due to possiblity of absolute path
- target_dir = os.path.expanduser('~') + target_dir[1]
- for item in structure:
- itype = item['type']
- fname = item['name']
- sub = item.get('sub', False)
- path = os.path.join(target_dir, fname)
- if itype == 'folder':
- if not os.path.isdir(path):
- os.makedirs(path)
- if sub:
- create_structure(path, sub)
- elif itype == 'file':
- content = item.get('content', False)
- with open(path, 'w+') as f:
- if content:
- f.write(content)
- else:
- logging.warn('Invalid type: [{}]'.format(itype))
- if __name__ == "__main__":
- create_structure('~/Desktop', [
- {
- "type": "folder",
- "name": "scripts",
- "sub": [
- {
- "type": "file",
- "name": "history.json"
- }
- ]
- },
- {
- "type": "folder",
- "name": "repos"
- },
- {
- "type": "file",
- "name": "history.json",
- "content": '''
- {
- 'name': 'test'
- }
- '''
- }
- ]
- )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement