Metadata-Version: 2.4
Name: echoss-fileformat
Version: 2.1.0
Summary: File format handler packages for JSON, CSV, XML, and Excel files
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.12
Description-Content-Type: text/markdown
Requires-Dist: echoss-common>=2.0.0
Requires-Dist: pandas<4,>=3.0
Requires-Dist: numpy>=1.26.0
Requires-Dist: pyarrow>=13.0.0
Requires-Dist: openpyxl>=3.1.5
Requires-Dist: xlrd>=2.0.1
Requires-Dist: lxml>=5.0.1
Requires-Dist: pyyaml>6.0.2
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"

# echoss_fileformat v2.1.0

# File Format Handlers

This project provides file format handler packages for JSON, CSV, XML, and Excel files. The packages provide an abstraction layer to load and save data in these file formats using a unified API.

## Version History
- v1.0 : Object method API
- v1.1 : static method API (FileUtil)
- v1.2 : stable update, parquet/feather 파일 포맷 지원
- v1.3 : echoss_logger 를 echoss-common 패키지로 이관, pytest 전환, Python 3.12+ 필요
- v2.0 : pandas 3.x, `load` 는 항상 DataFrame 하나(경로 목록·glob 패턴 지원), `processing_type` 폐기 예고, 구성 파일(`dict_load`/`dict_dump`)은 전부 echoss-common 2.x 에 위임, DB 결과 조각 이어쓰기(`FileUtil.dump_chunks`) — 아래 「2.0 호환성 변경」
- v2.1 : 조각 이어쓰기 형식 이름 `timestamp[ms,UTC]`(OpenSearch date, epoch 밀리초 정수 그대로)·`json_object`(dict)·`json_array`(list) 추가 — json 열은 JSON 문자열로 저장, 한 열에 한 모양(값과 배열이 섞이면 `ChunkTypeError`)

## Installation

To install the package, use pip:
pip install echoss_fileformat

To upgrade the installed package, use pip:
pip install echoss_fileformat -U

## Usage

1. static call 

```python
from echoss_fileformat import FileUtil, to_table, get_logger, set_logger_level

# FileUtil Load test_data from a file
csv_df = FileUtil.load('test_data.csv')
excel_df = FileUtil.load('weather_data.xls')
json_df = FileUtil.load('test_data.json', data_key = 'data')
jsonl_df = FileUtil.load('test_multiline_json.jsonl', data_key = 'data')

# FileUtil Save DataFrame to a file
FileUtil.dump(excel_df, 'save/test_data_1.csv')
FileUtil.dump(csv_df, 'weather_data.xlsx')
FileUtil.dump(json_df, 'test_data_2.jsonl')

# read/write config file
app_config = FileUtil.dict_load('config/application.yaml')
db_config = FileUtil.dict_load('jdbc.properties')
FileUtil.dict_dump(app_config, 'new_config.xml')

# DataFrame to table-like string
logger = get_logger("echoss_fileformat_test")
set_logger_level("DEBUG")
logger.debug(to_table(json_df))
```

파일 포맷 읽기 :
- FileUtil.load(file_path: str, file_format=None, **kwargs) : 파일 확장자 기준으로 매칭되는 파일포맷으로 읽음
  * 확장자 .csv : 기본csv 파일 포맷으로 읽기. 컬럼 구분자는 콤마(,) 사용.
  * 확장자 .tsv : 컬럼 구분자 탭(\t)인 csv 파일 포맷으로 읽기.
  * 확장자 .xls .xlsx : excel 파일 포맷으로 읽기
  * 확장자 .json : 파일 전체가 1개의 json 객체인 파일포맷으로읽기 (전체가 JSON array 인경우는 객체로 감싸야함)
  * 확자자 .jsonl : 라인 하나가 json  객체인 multi line json 파일 형태
  * 확장자 .xml : xml 파일포맷으로 읽기
  * 확장자 .parquet : parquet 파일포맷으로 읽기
  * 확장자 .feather : feather 파일포맷으로 읽기
- FileUtil.load(filename_or_file, file_format='csv') :  csv 파일 포맷으로 파일명  또는 file-like object 로 읽음
- FileUtil.load(filename_or_file, file_format='xlsx') :  excel 파일 포맷으로 파일명  또는 file-like object 로 읽음
- FileUtil.load(filename_or_file, file_format='json') :  json 파일 포맷으로 파일명  또는 file-like object 로 읽음

파일 포맷 쓰기 :
- FileUtil.dump(df: pd.DataFrame, file_path: str, file_format=None, force_write=False, **kwargs) : 파일 확장자 기준으로 매칭되는 파일포맷으로 쓰기
  * 확장자 .csv : 기본csv 파일 포맷으로 쓰기. 컬럼 구분자는 콤마(,) 사용.
  * 확장자 .tsv : 컬럼 구분자 탭(\t)인 csv 파일 포맷으로 쓰기.
  * 확장자 .xls .xlsx : excel 파일 포맷으로 쓰기
  * 확장자 .json : 파일 전체가 1개의 json 객체인 파일포맷으로쓰기 (전체가 JSON array 인경우는 객체로 감싸야함)
  * 확자자 .jsonl : 라인 하나가 json  객체인 multi line json 파일 형태
  * 확장자 .xml : xml 파일포맷으로 쓰기
  * 확장자 .parquet : parquet 파일포맷으로 쓰기
  * 확장자 .feather : feather 파일포맷으로 쓰기
- FileUtil.dump(filename_or_file, file_format='jsonl') :  jsonl 파일 포맷으로 파일명  또는 file-like object 로 쓰기
- FileUtil.dump_xml(filename_or_file, file_format='xml', force_write=True) :  xml 파일 포맷으로 overwrite 파일 쓰기

For config file load/dump:

dict_load() : load file format to dictionary for configuration files .yaml, .xml, .json and .properties
dict_dump() : write dictionary to file format  .yaml, .xml, .json and .properties

For print dataframe:

def to_table(df: pd.DataFrame, index=True, max_cols=16, max_rows=10, col_space=4, max_colwidth=24, fmt='grid'): 
dataframe to table-like string

exampe:
```
+--------------------------+----------------+----------------+---------------+--------------------+------------------+-----------------+-----------------+
| ('수집항목', '개체번호') | ('과폭', 'cm') | ('과고', 'cm') | ('과중', 'g') | ('당도', 'Brix %') | ('산도', '0-14') | ('경도', 'kgf') | ('수분율', '%') |
+--------------------------+----------------+----------------+---------------+--------------------+------------------+-----------------+-----------------+
| 1                        | 8.2            | 6.6            | 253           | 3.1                | 4.0              | 2.71            | 71.2            |
+--------------------------+----------------+----------------+---------------+--------------------+------------------+-----------------+-----------------+
| 2                        | 6.3            | 5.7            | 136           | 3.1                | 4.0              | 2.74            | 72.2            |
+--------------------------+----------------+----------------+---------------+--------------------+------------------+-----------------+-----------------+
| 3                        | 8.0            | 6.3            | 220           | 3.4                | 4.5              | 2.71            | 70.4            |
+--------------------------+----------------+----------------+---------------+--------------------+------------------+-----------------+-----------------+
| 4                        | 7.3            | 6.0            | 173           | 3.7                | 4.0              | 2.75            | 73.78           |
+--------------------------+----------------+----------------+---------------+--------------------+------------------+-----------------+-----------------+
| 5                        | 6.3            | 5.5            | 130           | 3.6                | 4.0              | 2.72            | 75.4            |
+--------------------------+----------------+----------------+---------------+--------------------+------------------+-----------------+-----------------+
```


2. Object 
- `processing_type` 은 생략한다. `load` 는 DataFrame 하나를 돌려준다 (`'object'`·`'array'`·`'multiline'` 은 2.0 에서 폐기 예고, 3.0 에서 제거)

handler = ExcelHandler()
df = handler.load('weather_data.xlsx')

- 여러 파일은 경로 목록이나 glob 패턴으로 한 번에 읽어 합친다

df = CsvHandler().load('data/temp_*.csv')

- JSON 파일 중에서 각 줄이 하나의 json 객체일 경우(jsonl)

df = JsonHandler().load('test_multiline_json.jsonl', lines=True)

- 메타데이터·설정처럼 DataFrame 이 아닌 객체는 `FileUtil.dict_load` 를 쓴다


The package provides an abstraction layer to load and save data in JSON, CSV, XML, and Excel formats. The API includes the following methods:

* `load(file_or_filename, **kwargs)`: Load data from a file.
* `loads(bytes_or_str, **kwargs)`: Load data from a string.
* `dump(file_or_filename, data = None, **kwargs)`: Save data to a file.
* `dumps(data = None, **kwargs)`: Save data to a string.

The following example demonstrates how to load data from a CSV file and save it as a JSON file:

```python
from echoss_fileformat import CsvHandler, JsonHandler

# Load test_data from a CSV file
csv_handler = CsvHandler()
data = csv_handler.load('test_data.csv', header=[0, 1])

# Save test_data as a JSON file
json_handler = JsonHandler()
json_df = json_handler.load(['test_data_1.json', 'test_data_2.json'], data_key = 'data')
json_handler.dump('test_data_all.json', json_df)
```

## 2.0 호환성 변경

- json·xml `load` 기본 반환이 DataFrame. Json·Xml `'object'` 제거(→ `FileUtil.dict_load`/`dict_dump`)
- `processing_type` 폐기 예고(`FutureWarning`), 새 기본 Handler 의 `to_pandas()` 는 `TypeError`
- json 저장은 항상 배열, dump 는 DataFrame 만
- 읽기에 성공한 파일이 하나도 없으면 모든 Handler 가 예외(Csv 의 `None` 반환·Json 의 빈 결과·Feather 의 `None` 반환이 사라짐 — 「`None` 이면 건너뜀」 코드는 예외 처리로). 여러 파일 중 일부 실패는 `fail_list` 로 보내고 나머지를 합침
- xls(Excel 97-2003) 쓰기는 조용한 실패 대신 `ValueError` — 읽기는 그대로
- `FileUtil.dump(df, '*.tsv')` 가 tsv 를 쓴다(전에는 오류 로그만 남기고 쓰지 않았다)
- 구성 파일(`FileUtil.dict_load`/`dict_dump`)은 모든 형식을 echoss-common 에 맡긴다. xml 결과가 바뀐다 — 속성은 `@이름`, 본문은 `#text`, 루트 요소 속성 포함, 주석 노드는 무시, 저장은 들여쓰기 없는 UTF-8. `XmlHandler.xml_to_dict`·`dict_to_xml`·`dict_dump` 제거
- 의존 하한 `echoss-common>=2.0.0` 으로 함께 바뀌는 것: 없는 구성 파일은 형식과 상관없이 `FileNotFoundError`(전에는 오류 로그와 빈 dict), 경로 없이 만든 로거는 `logs/echoss.log` 를 만들지 않고 콘솔에만 쓴다(파일이 필요하면 `file_path`·`new_path` 지정), YAML 저장은 넣은 순서 유지, 구성 파일은 항상 UTF-8

## Contributing
Contributions are welcome! If you find a bug or want to suggest a new feature, please open an issue on the GitHub repository.

## License
This project is licensed under the LGPL License. See the LICENSE file for more information.

## Credits
This project was created by 12cm. Special thanks to 12cm R&D for their contributions to the project.
