files.py 1.0 KB

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