2023. 12. 8. 16:09ㆍDevelopers 공간 [Shorts]/Software Basic
<분류>
A. 수단
- OS/Platform/Tool : Linux, Kubernetes(k8s), Docker, AWS
- Package Manager : node.js, yarn, brew,
- Compiler/Transpillar : React, Nvcc, gcc/g++, Babel, Flutter
- Module Bundler : React, Webpack, Parcel
B. 언어
- C/C++, python, Javacsript, Typescript, Go-Lang, CUDA, Dart, HTML/CSS
C. 라이브러리 및 프레임워크 및 SDK
- OpenCV, OpenCL, FastAPI, PyTorch, Tensorflow, Nsight
1. What? (현상)
이번엔 python에서 데이터를 다룰 때 자주 사용하는 json과 yaml, 그리고 csv 파일을 읽고 쓰는 방법은 간단히 정리해보려고 합니다.
일반적으로 python에서 파일을 읽고 쓰는 형식은 아래와 같습니다.
- 쓰기
# Case1 with open('test_file.txt','w') as f: f.write("The first line"+'\n') f.write("The second line"+'\n') f.write("The third line"+'\n') # Case2 f = open('test_file.txt','w') f.write("The first line"+'\n') f.write("The second line"+'\n') f.write("The third line"+'\n') f.close()
- 읽기
# Case1 with open('test_file.txt', 'r') as f: line = f.readline() # Case2 with open('test_file.txt', 'r') as f: lines = f.readlines() for line in lines: print(line) # Case3 f = open('test_file.txt','r') lines = f.readlines() for line in lines: print(line) f.close()
2. Why? (원인)
- X
3. How? (해결책)
먼저 아래와 같은 dictionary 혹은 리스트 데이터가 있다고 가정하겠습니다.
# Yaml과 Json에 활용 temp_dict = { 'A' : 1, 'B' : ['aa', 'bb', 'cc'], 'C' : {'aaa':111, 'bbb':222} } # CSV에 활용 field = ['id', 'name', 'string'] temp_dict2 = [ {'id':'0', 'name':'A', 'string':'aa'}, {'id':'1', 'name':'B', 'string':'bb'}, {'id':'2', 'name':'C', 'string':'cc'}, ] temp_list = [ ['id', 'name', 'string'], ['0', 'A', 'aa'], ['1', 'B', 'bb'], ['2', 'C', 'cc'], ]
1. Yaml
yaml(야믈)은 데이터 직렬화 언어로, json, xml과 같이 데이터 전송 형식을 가집니다.
- 설치
pip3 install pyyaml
- 패키지 import
import yaml
- 쓰기
with open('yaml_file.yaml', 'w') as f: yaml.dump(temp_dict, f)
- 읽기
with open('yaml_file.yaml', 'r') as f: yaml_data = yaml.full_load(f) yaml_data['A'] yaml_data['B'][0] yaml_data['C']['aaa']
with open('yaml_file.yaml', 'r') as f: yaml_data = yaml.load(f, Loader=yaml.FullLoader) yaml_data['A'] yaml_data['B'][0] yaml_data['C']['aaa']
with open('yaml_file.yaml', 'r') as f: yaml_data = yaml.safe_load(f) yaml_data['A'] yaml_data['B'][0] yaml_data['C']['aaa']
2. Json
Json은 yaml과 마찬가지로 데이터 전송형식을 가집니다.
- 설치
pip3 install json
- 패키지 import
import json
- 쓰기
with open('json_file.json', 'w', encoding='utf-8') as f: json.dump(temp_dict, f, indent="\t")
만약 json에 위 temp_dict 형태가 아닌 temp_dict2처럼 여러개의 dictionary 형태로 되어있다면 아래와 같이 여러번 dump하면서 개행문자를 입력해주면 됩니다. 이와 같이 json이 여러줄 있는 것을 jsonl 포맷이라고 합니다.
with open('json_file.jsonl', 'w', encoding='utf-8') as f: json.dump(temp_dict, f, indent="\t", ensure_ascii=Fales) f.write("\n")
- 읽기
with open('json_file.json', 'r') as f: json_data = json.load(f) json_data['A'] json_data['B'][0] json_data['C']['aaa'] json.dumps(json_data) json.dumps(json_data, indent="\t")
만약 json에 위 temp_dict 형태가 아닌 temp_dict2처럼 여러개의 dictionary 형태로 되어있다면 아래와 같은 에러가 날 것입니다.
json.decoder.JSONDecoderError: Extra data: line 2 column 1
이럴 때는 여러번 읽는 것으로 대체 해야 합니다.
with open('json_file.json', 'r') as f: json_data = [json.loads(line) for line in f] json_data[0]['id'] json_data[0]['name'] json_data[0]['string'] json.dumps(json_data[0]) json.dumps(json_data[0], indent="\t")
3. CSV(Comma-Separated Values)
CSV는 말그대로 ','로 구분된 텍스트 데이터 입니다. 이런 형식은 Excel로 읽을 수도 있기 때문에, 데이블 형태로 구성된 데이터를 다룰 때 주로 사용됩니다.
- 설치
pip3 install csv
- 패키지 import
import csv
- 쓰기
with open('csv_file.csv', 'w') as f: writer = csv.writer(f) writer.writerows(temp_list) writer.writerow(temp_list[0])
with open('csv_file.csv', 'w') as f: writer = csv.DictWriter(f, fieldnames=field) writer.writeheader() writer.writerows(temp_dict2)
- 읽기
with open('csv_file.csv', 'r') as f: reader= csv.reader(f) data = list(reader) for row in data: print(row)
with open('csv_file.csv', 'r') as f: reader= csv.DictReader(f) data = list(reader) for row in data: print(row)
'Developers 공간 [Shorts] > Software Basic' 카테고리의 다른 글
[Docker] Dockerfile 내 상위 디렉토리 COPY하고 싶을 때 (0) | 2023.12.30 |
---|---|
[Python] Python과 PyTorch Copy 에 대해서 (0) | 2023.12.16 |
[Docker] no space left on device (0) | 2023.11.18 |
[PyTorch] 특정 GPU로 정해 동작시키기 (1) | 2023.11.08 |
[Bash] 파일명을 활용해 작업하는 기초 명령어 (2) | 2023.11.03 |