Coverage for gib_esu/helpers/py_utils.py: 100%
16 statements
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-25 16:39 +0300
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-25 16:39 +0300
1import csv
2import io
3from typing import Dict, List, Union
6class PyUtils:
7 """Class encapsulating various python utility methods."""
9 @classmethod
10 def read_csv(
11 cls, filepath_or_buffer: Union[str, io.StringIO]
12 ) -> List[Dict[str, str]]:
13 """Reads input data from a CSV file or string stream.
15 Args:
16 filepath_or_buffer (Union[str, io.StringIO]): Path to a CSV file
17 or a string stream containing CSV data.
19 Returns:
20 List[Dict[str, str]]: A list of dictionaries representing rows in the CSV
21 with all fields as strings.
22 """
24 if isinstance(filepath_or_buffer, str) and not isinstance(
25 filepath_or_buffer, io.StringIO
26 ):
27 file = open(filepath_or_buffer, mode="r", encoding="utf-8")
28 else:
29 file = filepath_or_buffer
31 with file:
32 reader = csv.DictReader(file)
34 records = []
35 for row in reader:
36 record = {
37 key: str(row.get(key, "") or "") for key in reader.fieldnames or []
38 }
39 records.append(record)
41 return records