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/) diff --git a/ezpkl/__init__.py b/ezpkl/__init__.py index f9d6132..2ed90a8 100644 --- a/ezpkl/__init__.py +++ b/ezpkl/__init__.py @@ -1,5 +1,6 @@ from ezpkl.pickling import load_pkl, save_pkl +from ezpkl.texting import save_txt, load_txt -__all__ = [save_pkl, load_pkl] +__all__ = [save_pkl, load_pkl, save_txt, load_txt] -__version__ = "0.1.7" +__version__ = "0.2.0" 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", +] diff --git a/ezpkl/texting.py b/ezpkl/texting.py new file mode 100644 index 0000000..e50eb19 --- /dev/null +++ b/ezpkl/texting.py @@ -0,0 +1,74 @@ +"""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, 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. + 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 + + 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 separator is None: + file.write("".join(str(item) for item in data)) + else: + file.write(separator.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) -> Union[str, None]: + """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 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") == "치유치유빔!✨"