about summary refs log tree commit diff
diff options
context:
space:
mode:
authorFrederick Muriuki Muriithi2024-10-21 16:56:30 -0500
committerFrederick Muriuki Muriithi2024-10-21 16:56:30 -0500
commit4204f636ab242e2b73d6a7c8ed1cd6b0c7b925ce (patch)
tree97252908b8d70e57f0fa6e07bd411f26a7433da7
parentc53b93a4aa1d165159144acca523011cd75d1531 (diff)
downloadgn-uploader-4204f636ab242e2b73d6a7c8ed1cd6b0c7b925ce.tar.gz
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.
-rw-r--r--r_qtl/r_qtl2.py18
1 files changed, 18 insertions, 0 deletions
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))