Skip to content

Commit

Permalink
Tighten up utils.write_csv and add a test
Browse files Browse the repository at this point in the history
  • Loading branch information
palewire committed Dec 22, 2022
1 parent 963cffe commit e83592b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
29 changes: 25 additions & 4 deletions newshomepages/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,34 @@ def safe_ia_handle(handle: str) -> str:
return s


def write_csv(dict_list, path):
"""Write a list of dictionaries to a CSV file."""
print(f"📥 Writing CSV to {path}")
fieldnames = dict_list[0].keys()
def write_csv(
dict_list: typing.List[typing.Dict], path: Path, verbose: bool = True
) -> None:
"""Write a list of dictionaries to a CSV file at the provided path.
Args:
data (Any): Any Python object ready to be serialized as JSON.
path (Path): The filesystem Path where the object should be written.
verbose (bool): Whether or not to log the action prior to execution. (Default: True)
Returns nothing.
"""
# Log it
if verbose:
print(f"📥 Writing CSV with {len(dict_list)} records to {path}")

# Open a file
with open(path, "w") as fh:
# Pop out the field names we'll use as the header
fieldnames = dict_list[0].keys()

# Fire up a writer
writer = csv.DictWriter(fh, fieldnames=fieldnames)

# Write out the header
writer.writeheader()

# Write out the data
writer.writerows(dict_list)


Expand Down
7 changes: 7 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ def test_safe_ia_handle():
pass


def test_write_csv(tmpdir):
"""Test write_csv."""
p = Path(tmpdir / "write_csv")
utils.write_csv([{"foo": "bar"}], p)
utils.write_csv([{"foo": "bar"}], p, verbose=False)


def test_write_json(tmpdir):
"""Test write_json."""
p = Path(tmpdir / "write_json")
Expand Down

0 comments on commit e83592b

Please sign in to comment.