files.py 934 B

1234567891011121314151617181920212223242526272829303132
  1. import os
  2. def build_files(file_defs, prefix=""):
  3. """
  4. Build a set of files/directories, as described by the file_defs dictionary.
  5. Each key/value pair in the dictionary is interpreted as a filename/contents
  6. pair. If the contents value is a dictionary, a directory is created, and the
  7. dictionary interpreted as the files within it, recursively.
  8. For example:
  9. {"README.txt": "A README file",
  10. "foo": {
  11. "__init__.py": "",
  12. "bar": {
  13. "__init__.py": "",
  14. },
  15. "baz.py": "# Some code",
  16. }
  17. }
  18. """
  19. for name, contents in file_defs.items():
  20. full_name = os.path.join(prefix, name)
  21. if isinstance(contents, dict):
  22. if not os.path.exists(full_name):
  23. os.makedirs(full_name)
  24. build_files(contents, prefix=full_name)
  25. else:
  26. with open(full_name, 'w') as f:
  27. f.write(contents)