csv.py 934 B

12345678910111213141516171819202122232425262728293031323334353637
  1. __package__ = 'archivebox.index'
  2. from typing import List, Optional, Any
  3. from archivebox.misc.util import enforce_types
  4. from .schema import Link
  5. @enforce_types
  6. def links_to_csv(links: List[Link],
  7. cols: Optional[List[str]]=None,
  8. header: bool=True,
  9. separator: str=',',
  10. ljust: int=0) -> str:
  11. cols = cols or ['timestamp', 'is_archived', 'url']
  12. header_str = ''
  13. if header:
  14. header_str = separator.join(col.ljust(ljust) for col in cols)
  15. row_strs = (
  16. link.to_csv(cols=cols, ljust=ljust, separator=separator)
  17. for link in links
  18. )
  19. return '\n'.join((header_str, *row_strs))
  20. @enforce_types
  21. def to_csv(obj: Any, cols: List[str], separator: str=',', ljust: int=0) -> str:
  22. from .json import to_json
  23. return separator.join(
  24. to_json(getattr(obj, col), indent=None).ljust(ljust)
  25. for col in cols
  26. )