Skip to content

Commit

Permalink
Merge ee058d9 into 2ced12f
Browse files Browse the repository at this point in the history
  • Loading branch information
yesinkim authored Sep 18, 2024
2 parents 2ced12f + ee058d9 commit 7359e00
Show file tree
Hide file tree
Showing 6 changed files with 238 additions and 9 deletions.
47 changes: 47 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/)
49 changes: 48 additions & 1 deletion README_ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
</h4>

![EZPKL character](https://raw.githubusercontent.com/yesinkim/ezpkl/main/assets/banner.png)
컨텍스트 매니저를 열고 닫는 것이 귀찮아서 만들었습니다.
컨텍스트 매니저 문법과 생김새를 좋아하지 않아서 만들었습니다.

## 설치

Expand Down Expand Up @@ -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/)
5 changes: 3 additions & 2 deletions ezpkl/__init__.py
Original file line number Diff line number Diff line change
@@ -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"
34 changes: 28 additions & 6 deletions ezpkl/refrigerator.py
Original file line number Diff line number Diff line change
@@ -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'
]
"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",
]
74 changes: 74 additions & 0 deletions ezpkl/texting.py
Original file line number Diff line number Diff line change
@@ -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
38 changes: 38 additions & 0 deletions tests/test_texting.py
Original file line number Diff line number Diff line change
@@ -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") == "치유치유빔!✨"

0 comments on commit 7359e00

Please sign in to comment.