[부스트캠프 AI tech Python Basic] week01 (2022.01.20)

redgreen·2022년 1월 20일
0

Python Basics for AI(4-2)

Module and Project

touch test.py #빈 파일 만들기
code test.py #vs code로 실행

__init__.py

  • 현재 폴더가 패키지임을 알리는 초기화 스크립트
  • 하위 폴더와 py파일(모듈)을 모두 포함함
  • import와 __all__ 키워드 사용

아나콘다 가상환경 생성

conda create -n my_project(이름) python=3.9(버전)

가상환경 활성화/비활성화

conda activate my_project
conda deactivate

Python Basics for AI(5-1)

File / Exception / Log Handling

assert

def get_binary_number(decimal_number : int):
	assert isinstance(decimal_number, int)
    return bin(decimal_number)   
print(get_binary_number(10.0))
return
AssertionError: 

File

read

f = open('file.txt', 'r')
contents = f.read()
contents_list = f.readlines()
print(contents)
f.close()
with open('file.txt', 'r') as my_file:
	contents = my_file.read()
    contents_list = my_file.readlines()
  • f.readline(): 한줄씩 읽어오기

write

f = open('file.txt', 'w', encoding='utf8')
for i in range(11):
	data = '%d번째 줄입니다.\n' % i 
    f.write(data)
f.close()
  • 'a'는 추가모드

OS module

try:
	os.mkdir('abc')
except FileExistsError as e:
	print('Already created')
os.path.exists('abc') #폴더
os.path.isfile('file.ipynb') #파일
import shutil
source = 'file.txt'
dest = os.path.join('abc', source)
shutil.copy(source, dest) # 복사
import pathlib
cwd = pathlib.Path.cwd() # 현재 디렉토리
cwd.parent.parents
list(cwd.parent.glob('*'))

Pickle

import pickle
f = open('list.pickle', 'wb')
test = [1,2,3,4,5]
pickle.dump(test, f)
f.close()
------------------------------
f = open('list.pickle', 'rb')
test_pickle = pickle.load(f)
f.close()

Logging


Python Basics for AI(5-2)

Python data handling

정규식 연습 사이트: https://regexr.com/

JSON: JavaScript Object Notation

  • XML을 간단히 줄일 수 있음
dict_data = {'Name' : 'Zara', 'Age' : 7, 'Class' : 'First'}
with open('data.json', 'w') as f:
	json.dump(dict_data, f)
profile
인공지능 꿈나무

0개의 댓글