From ae125c340bb187bf0fb45ae3dec355c3d3d72029 Mon Sep 17 00:00:00 2001 From: "Haoyu (Daniel)" Date: Thu, 5 Sep 2024 17:41:03 +0800 Subject: [PATCH] use unix line ending \n as default if empty --- src/monty/io.py | 4 +++- tests/test_io.py | 16 +++++++++------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/monty/io.py b/src/monty/io.py index 487ada910..0ffda9bb3 100644 --- a/src/monty/io.py +++ b/src/monty/io.py @@ -13,6 +13,7 @@ import os import subprocess import time +import warnings from pathlib import Path from typing import TYPE_CHECKING @@ -80,7 +81,8 @@ def _get_line_ending( raise TypeError(f"Unknown file type {type(file).__name__}") if not first_line: - raise ValueError("empty file.") + warnings.warn("File empty, use default line ending \n.", stacklevel=2) + return "\n" if first_line.endswith(b"\r\n"): return "\r\n" diff --git a/tests/test_io.py b/tests/test_io.py index ef8dd2c77..5258d49be 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -65,8 +65,8 @@ def test_empty_file(self): test_file = "empty_file.txt" open(test_file, "w").close() - with pytest.raises(ValueError, match="empty file"): - _get_line_ending(test_file) + with pytest.warns(match="File empty, use default line ending \n"): + assert _get_line_ending(test_file) == "\n" def test_unknown_line_ending(self): with ScratchDir("."): @@ -119,9 +119,10 @@ def test_empty_file(self): Make sure an empty file does not throw an error when reverse_readline is called, which was a problem with an earlier implementation. """ - with open(os.path.join(TEST_DIR, "empty_file.txt")) as f: - for _line in reverse_readline(f): - raise ValueError("an empty file is being read!") + with pytest.warns(match="File empty, use default line ending \n."): + with open(os.path.join(TEST_DIR, "empty_file.txt")) as f: + for _line in reverse_readline(f): + raise ValueError("an empty file is being read!") @pytest.fixture() def test_line_ending(self): @@ -189,8 +190,9 @@ def test_empty_file(self): Make sure an empty file does not throw an error when reverse_readline is called, which was a problem with an earlier implementation. """ - for _line in reverse_readfile(os.path.join(TEST_DIR, "empty_file.txt")): - raise ValueError("an empty file is being read!") + with pytest.warns(match="File empty, use default line ending \n."): + for _line in reverse_readfile(os.path.join(TEST_DIR, "empty_file.txt")): + raise ValueError("an empty file is being read!") @pytest.fixture def test_line_ending(self):