From 4204f636ab242e2b73d6a7c8ed1cd6b0c7b925ce Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Mon, 21 Oct 2024 16:56:30 -0500 Subject: Add utilities for reading text files and csv files The function `read_text_file(…)` will read the raw text file and return the content line by line. The function `read_csv_file(…)` builds on `read_text_file(…)` to read a file as a character-separated-values file. The field separator, and comment_char characters can be provided to customise how the CSV file is read. --- r_qtl/r_qtl2.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/r_qtl/r_qtl2.py b/r_qtl/r_qtl2.py index ad9271c..5b926d1 100644 --- a/r_qtl/r_qtl2.py +++ b/r_qtl/r_qtl2.py @@ -554,3 +554,21 @@ def load_samples(zipfilepath: Union[str, Path], pass return tuple(samples) + + + +def read_text_file(filepath: Union[str, Path]) -> Iterator[str]: + """Read the raw text from a text file.""" + with open(filepath, "r", encoding="utf8") as _file: + for line in _file: + yield line + + +def read_csv_file(filepath: Union[str, Path], + separator: str = ",", + comment_char: str = "#") -> Iterator[str]: + """Read a file as a csv file.""" + for line in read_text_file(filepath): + if line.startswith(comment_char): + continue + yield tuple(field.strip() for field in line.split(separator)) -- cgit v1.2.3