From 26c937f562b2194f25c3120352a6d1227d28e4de Mon Sep 17 00:00:00 2001 From: yesinkim Date: Tue, 27 Aug 2024 23:02:52 +0900 Subject: [PATCH 1/5] =?UTF-8?q?feat:=20add=20ingredient=20mel=C3=B3n=20y?= =?UTF-8?q?=20jam=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ezpkl/refrigerator.py | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/ezpkl/refrigerator.py b/ezpkl/refrigerator.py index d8ed63a..8c903f3 100644 --- a/ezpkl/refrigerator.py +++ b/ezpkl/refrigerator.py @@ -1,7 +1,29 @@ ingredients = [ - 'apricot', 'broccoli', 'cherry', 'date', 'elderberry', - 'fig', 'grape', 'honeydew', 'iceberg', 'jalapeno', - 'kiwi', 'lime', 'mushroom', 'nectarine', 'olive', - 'pumpkin', 'quince', 'raspberry', 'strawberry', 'tangerine', - 'uglifruit', 'vanilla', 'watermelon', 'xigua', 'yam', 'zucchini' -] \ No newline at end of file + "apricot", + "broccoli", + "cherry", + "date", + "elderberry", + "fig", + "grape", + "honeydew", + "iceberg", + "jalapeno", + "kiwi", + "lime", + "mushroom", + "nectarine", + "olive", + "pumpkin", + "quince", + "raspberry", + "strawberry", + "tangerine", + "uglifruit", + "vanilla", + "watermelon", + "xigua", + "yam", + "zucchini" "jamon", + "melon", +] From 4e1f2c1449e14a2a3db0bf788d9ccdc03bf2408d Mon Sep 17 00:00:00 2001 From: yesinkim Date: Wed, 28 Aug 2024 12:26:44 +0900 Subject: [PATCH 2/5] feat: add handling txt file --- ezpkl/__init__.py | 3 +- ezpkl/texting.py | 74 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 ezpkl/texting.py diff --git a/ezpkl/__init__.py b/ezpkl/__init__.py index 2d5fbb1..23af412 100644 --- a/ezpkl/__init__.py +++ b/ezpkl/__init__.py @@ -1,3 +1,4 @@ from ezpkl.pickling import load_pkl, save_pkl +from ezpkl.texting import save_txt, load_txt -__version__ = "0.1.4" +__version__ = "0.2.0" diff --git a/ezpkl/texting.py b/ezpkl/texting.py new file mode 100644 index 0000000..3708237 --- /dev/null +++ b/ezpkl/texting.py @@ -0,0 +1,74 @@ +"""Make your life simply""" + +import inspect +import random + +from ezpkl.refrigerator import ingredients + + +def save_txt(data, file_name: str = None, newline: bool = True) -> None: + """Saves data to a text file. + + Args: + data: The data to be saved. Can be a string, list, or any other object that can be converted to a string. + file_name: The name of the text file. If not provided, the function attempts to determine the variable name from the previous frame's local variables. + newline: Whether to add a newline character at the end of each line. Defaults to True. + + Returns: + None + + Raises: + FileNotFoundError: If the file cannot be found. + PermissionError: If there is a permission error while saving the file. + """ + var_name = None + frame = inspect.currentframe() + try: + if not file_name: + previous_frame = frame.f_back + for name, value in previous_frame.f_locals.items(): + if value is data: + var_name = name + break + if var_name: + file_name = f"{var_name}.txt" + else: + file_name = f"{random.choice(ingredients)}.txt" + print("I couldn't find the variable name, but here's some ingredient for you instead!") + elif not file_name.endswith(".txt"): + file_name = f"{file_name}.txt" + + try: + with open(file_name, "w") as file: + if isinstance(data, list): + if newline: + file.write("\n".join(str(item) for item in data)) + else: + file.write(" ".join(str(item) for item in data)) + else: + file.write(str(data)) + print(f"Data saved to '{file_name}'.") + except (FileNotFoundError, PermissionError) as e: + print(f"Error saving data: {str(e)}") + finally: + del frame + + +def load_txt(filename: str): + """Loads data from a text file. + + Args: + filename: The name of the text file. + + Returns: + The data loaded from the file, or None if the file is not found. + + Raises: + FileNotFoundError: If the file cannot be found. + """ + try: + with open(filename, "r") as file: + return file.read() + except FileNotFoundError: + print(f"File '{filename}' not found.") + return None From 78e16277ed8fa38d17bd3d4e4cbe73412fc89e26 Mon Sep 17 00:00:00 2001 From: yesinkim Date: Wed, 18 Sep 2024 18:46:43 +0900 Subject: [PATCH 3/5] feat: add txt function --- ezpkl/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ezpkl/__init__.py b/ezpkl/__init__.py index 23af412..2ed90a8 100644 --- a/ezpkl/__init__.py +++ b/ezpkl/__init__.py @@ -1,4 +1,6 @@ from ezpkl.pickling import load_pkl, save_pkl from ezpkl.texting import save_txt, load_txt +__all__ = [save_pkl, load_pkl, save_txt, load_txt] + __version__ = "0.2.0" From 22241357870240bab46fae29841a80f5d191b65a Mon Sep 17 00:00:00 2001 From: yesinkim Date: Wed, 18 Sep 2024 19:26:14 +0900 Subject: [PATCH 4/5] feat: add texting function --- ezpkl/texting.py | 14 +++++++------- tests/__init__.py | 0 tests/test_texting.py | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 7 deletions(-) create mode 100644 tests/__init__.py create mode 100644 tests/test_texting.py diff --git a/ezpkl/texting.py b/ezpkl/texting.py index 3708237..e50eb19 100644 --- a/ezpkl/texting.py +++ b/ezpkl/texting.py @@ -1,18 +1,18 @@ """Make your life simply""" - import inspect import random +from typing import Union from ezpkl.refrigerator import ingredients -def save_txt(data, file_name: str = None, newline: bool = True) -> None: +def save_txt(data, file_name: str = None, separator: str = "\n") -> None: """Saves data to a text file. Args: data: The data to be saved. Can be a string, list, or any other object that can be converted to a string. file_name: The name of the text file. If not provided, the function attempts to determine the variable name from the previous frame's local variables. - newline: Whether to add a newline character at the end of each line. Defaults to True. + separator: The separator to use between items in a list. Defaults to "\n", which means items will be joined with a newline character. Returns: None @@ -41,10 +41,10 @@ def save_txt(data, file_name: str = None, newline: bool = True) -> None: try: with open(file_name, "w") as file: if isinstance(data, list): - if newline: - file.write("\n".join(str(item) for item in data)) + if separator is None: + file.write("".join(str(item) for item in data)) else: - file.write(" ".join(str(item) for item in data)) + file.write(separator.join(str(item) for item in data)) else: file.write(str(data)) print(f"Data saved to '{file_name}'.") @@ -54,7 +54,7 @@ def save_txt(data, file_name: str = None, newline: bool = True) -> None: del frame -def load_txt(filename: str): +def load_txt(filename: str) -> Union[str, None]: """Loads data from a text file. Args: diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_texting.py b/tests/test_texting.py new file mode 100644 index 0000000..93bfbb2 --- /dev/null +++ b/tests/test_texting.py @@ -0,0 +1,38 @@ +import pytest + +from ezpkl import load_txt, save_txt + + +def test_save_txt_string(): + data = "안뇽 세상!" + save_txt(data, file_name="test_string") + assert load_txt("test_string.txt") == data + + +def test_save_txt_list(): + data = ["apple", "banana", "cherry"] + save_txt(data, file_name="test_list") + assert load_txt("test_list.txt") == "\n".join(data) + + +def test_save_txt_invalid_filename(): + data = "춘의 쾌유를 빕니다" + save_txt(data, file_name="test.txt") + assert load_txt("test.txt") == data + + +def test_load_txt_nonexistent_file(): + filename = "nonexistent_file.txt" + assert load_txt(filename) is None + + +def test_save_txt_no_filename_with_variable(): + data = "This is a test." + save_txt(data) + assert load_txt("data.txt") == data + + +def test_save_txt_with_separator(): + data = ["치유", "치유", "빔", "!", "✨"] + save_txt(data, separator=None) + assert load_txt("data.txt") == "치유치유빔!✨" From 1df149c4a5054c94eb17bf707b5f84f7a4605865 Mon Sep 17 00:00:00 2001 From: yesinkim Date: Wed, 18 Sep 2024 19:39:24 +0900 Subject: [PATCH 5/5] docs: write readme --- README.md | 47 +++++++++++++++++++++++++++++++++++++++++++++++ README_ko.md | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 95 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f063856..ffde0fa 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,53 @@ from ezpkl import load_pkl a = load_pkl('a.pkl') ``` +### Save Object to txt + +```python +from ezpkl import save_txt + +a = [1, 2, 3, 4, 5] + +# 'a.txt' will be saved in the current directory. +save_txt(data=a) + +# 'a_list_temp.txt' will be saved in the current directory. +save_txt(data=a, file_name='a_list_temp') +``` + +### Load Object + +```python +from ezpkl import load_txt + +a = load_txt('a.txt') +``` + +### Save List Object to txt with separator + +```python +from ezpkl import save_txt + +a = ["apple", "banana", "cherry"] + +# 'a.txt' will be saved in the current directory with newline separator (default). +save_txt(data=a) +# a.txt file content: +# apple +# banana +# cherry + +# 'a_list_temp.txt' will be saved in the current directory with space separator. +save_txt(data=a, file_name='a_list_temp', separator=' ') +# a_list_temp.txt file content: +# apple banana cherry + +# 'a_list_temp.txt' will be saved in the current directory without separator. +save_txt(data=a, file_name='a_list_temp', separator=None) +# a_list_temp.txt file content: +# applebananacherry +``` + ## License [MIT](https://choosealicense.com/licenses/mit/) diff --git a/README_ko.md b/README_ko.md index b806b56..d19b501 100644 --- a/README_ko.md +++ b/README_ko.md @@ -10,7 +10,7 @@ ![EZPKL character](https://raw.githubusercontent.com/yesinkim/ezpkl/main/assets/banner.png) -컨텍스트 매니저를 열고 닫는 것이 귀찮아서 만들었습니다. +컨텍스트 매니저 문법과 생김새를 좋아하지 않아서 만들었습니다. ## 설치 @@ -44,6 +44,53 @@ from ezpkl import load_pkl a = load_pkl('a.pkl') ``` +### 객체를 txt로 저장하기 + +```python +from ezpkl import save_txt + +a = [1, 2, 3, 4, 5] + +# 현재 폴더에 'a.txt'가 저장됩니다. +save_txt(data=a) + +# 현재 폴더에 'a_list_temp.txt'가 저장됩니다. +save_txt(data=a, file_name='a_list_temp') +``` + +### 객체 불러오기 + +```python +from ezpkl import load_txt + +a = load_txt('a.txt') +``` + +### 구분자를 사용하여 리스트 객체를 txt로 저장하기 + +```python +from ezpkl import save_txt + +a = ["apple", "banana", "cherry"] + +# 기본 구분자(줄바꿈)로 현재 폴더에 'a.txt'가 저장됩니다. +save_txt(data=a) +# a.txt 파일 내용: +# apple +# banana +# cherry + +# 공백 구분자로 현재 폴더에 'a_list_temp.txt'가 저장됩니다. +save_txt(data=a, file_name='a_list_temp', separator=' ') +# a_list_temp.txt 파일 내용: +# apple banana cherry + +# 구분자 없이 현재 폴더에 'a_list_temp.txt'가 저장됩니다. +save_txt(data=a, file_name='a_list_temp', separator=None) +# a_list_temp.txt 파일 내용: +# applebananacherry +``` + ## 라이선스 [MIT](https://choosealicense.com/licenses/mit/)