일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- ubuntu
- windows forms
- 기타 연주
- pytorch
- C#
- OpenCV
- LIST
- Visual Studio
- 핑거스타일
- YOLO
- JSON
- Selenium
- SSH
- paramiko
- error
- pip
- 프로그래머스
- VS Code
- label
- C++
- Numpy
- pandas
- mysql
- 컨테이너
- Linux
- 오류
- 채보
- C
- Python
- Docker
- Today
- Total
목록Python (115)
기계는 거짓말하지 않는다
Python 3.7 버전부터 기본 Dict도 삽입 순서를 보장한다. 명시적으로는 collections 모듈의 OrderedDict를 사용할 수 있다. Python Ordered Dict 문서 collections — Container datatypes Source code: Lib/collections/__init__.py This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.,,... docs.python.org 아래와 같이 사용할 수 있다. from collections import..
입력받거나 작성된 경로가 절대 경로인지 확인하고 상대 경로이면 절대 경로로, 절대 경로이면 상대 경로로 변환한다. import os data_path = "../../Temp/aa.txt" if not os.path.isabs(data_path): # 절대 경로 변환 data_path = os.path.abspath(data_path) print("abs path:", data_path) else: # 상대 경로 변환 data_path = os.path.relpath(data_path) print("relative path:", data_path)
Python에서 추상클래스를 생성하는 방법이다. abc 모듈이 필요하고 추상클래스의 추상메소드가 존재할 때, 객체를 생성하면 예외가 발생한다. 추상클래스를 상속받은 하위 클래스는 추상메소드를 구현하지 않으면 예외가 발생한다. from abc import * class TempAbstractClass(metaclass=ABCMeta): @abstractmethod def show_val(self): pass class TempClass(TempAbstractClass): def __init__(self, n: int, s: str): self.number = n self.string = s def show_val(self): print(f"Values: {self.number}, {self.string}"..
cv2를 이용할 때 imread, imwrite 한글(utf-8) 인식 문제가 있다. imread, imwrite 함수를 아래와 같이 선언하고 사용한다. import os import cv2 import numpy as np def imread(file_path): npArr = np.fromfile(file_path, dtype=np.uint8) return cv2.imdecode(npArr, cv2.IMREAD_COLOR) def imwrite(file_path, img, params=None): try: ext = os.path.splitext(file_path)[1] result, n = cv2.imencode(ext, img, params) if result: with open(file_path..
문자열은 immutable이므로 문자 수정이 불가능하다. List 변경 후 다시 문자열로 변환하는 방법이 있다. temp_str = "ABCDEF" temp_str = list(temp_str) temp_str[0] = "g" temp_str[1] = "h" temp_str = "".join(temp_str) print(f"Change String: {temp_str} (Type: {type(temp_str)})")
디렉터리 내의 파일들의 경로를 텍스트 파일로 저장한다. 특정 확장자만 제한하려면 argparser로 넘겨준다. argparser 명령어 예시 image_files 디렉터리 내의 png, jpg, jpeg 확장자를 가진 파일들의 경로를 file_list.txt 텍스트 파일로 저장 python file_path_list_to_text.py -p ./image_files -t file_list.txt -e png jpg jpeg import glob import argparse import os def parse_opt(): parser = argparse.ArgumentParser() parser.add_argument('-p', '--path', default=".", help="data path") pa..
리스트의 선언, 할당 과정을 간단하게 한 줄로 처리할 수 있다. 리스트 내포의 간단한 사용 예시이다. # 순차 할당 temp_list = [i for i in range(10)] print(temp_list, "\n", "-" * 40) # 2중 반복 temp_list = [j for i in range(3) for j in range(5)] print(temp_list, "\n", "-" * 40) # 조건문 temp_list = [i for i in range(10) if i > 5 or i < 2] print(temp_list, "\n", "-" * 40) # 대입 값 조건문 temp_list = [i if i < 5 else -1 for i in range(10)] print(temp_list, ..
직접 구현해도 상관없지만 os.path 모듈에서 지원한다. import os file_path = "D:/TempRoot/TempChild/temp_file.txt" # 경로에서 확장자 분리 후 튜플로 반환 print(os.path.splitext(file_path)) split_ext = os.path.splitext(file_path) print("Type:", type(split_ext)) print("Index[0]:", split_ext[0]) print("Index[1]:", split_ext[1], "\n") # 경로에서 파일이름 분리 후 튜플로 반환 print(os.path.split(file_path)) split_file_name = os.path.split(file_path) prin..