코드 관리의 용이성
: 코드가 길어지면 한 개 파일에 모든 코드를 넣고 관리하기 어렵다
실행의 효율성
: 긴 코드는 메모리 용량을 많이 차지해 실행 시간이 오래 걸린다
재사용성: 관련 함수나 클래스들을 한 개 파일에 묶으면 재사용이 쉽다
그렇다면 모듈에 대해 학습해보자
1) import 모듈이름
2) from 모듈이름 import 모듈 내 클래스 이름
3) 한꺼번에 불러오기: import Rectangle, Circle
#Retangle.py
class Rectangle:
def __init__(self,x1,y1,x2,y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def calcArea(self):
width = abs(self.x2 - self.x1)
heigth = abs(self.y2 - self.y1)
return width * heigth
#Circle.py
import math
class Circle:
def __init__(self,x,y,r):
self.x = x
self.y = y
self.r = r
def calcArea(self):
return math.pi *(self.r ** 2)
import Rectangle, Circle
r = Rectangle.Rectangle(1,2,3,4)
c = Circle.Circle(1,3,5)
print(r.calcArea()) #Rectangel 내 calcArea() 불러와 계산
print(c.calcArea()) #Circle내 calcArea() 불러와 계산
import Rectangle
r = Rectangle.Rectangle(10, 20, 20, 10)
print(r.calcArea())
#Cicle.py
pi = 3.1415
def circumference(r):
return 2 * pi * r
class Circle1:
def __init__(self,r):
self.r = r
def getCircumference(self):
return circumference(self.r)
#test.py
import Circle
print(Circle.pi)
print(f"반지름이 10인 원 둘레: {Circle.circumference(10): .2f}")
c = Circle.Circle1(5)
print(c.getCircumference())
# 직접 실행된 경우
__name__ = __main__
# 모듈로 임포트 된 경우
__name__ = 스크립트 한 파일 이름(확장자 제외)
#dice5
import random
def throwDice():
return random.randint(1, 6)
if __name__ == "__main__":
print("testing throwDice()")
for i in range(10):
print(throwDice(), end = ' ')
print("")
# TestDice5.py
import dice5
print("Testing dice5 module")
print(f"TestDice5: __name__ = {__name__}") #TestDice5 실행
for i in range(3):
print(dice5.throwDice())
# 동작 이해하기
1) dice5를 import 해온다
2) dice5가 실행된다 -> dice5에서 직접 실행되는 것이 아니기 때문에 if문 실행 x
3) TestDice5에서 print문 실행
4) TestDice5가 직접 실행되기 때문에 __name__ = __main__
5) 아래 for문 반복
>> Testing dice5 module
>> TestDice5: __name__ = __main_
>> 4
>> 2
>> 6
#pip 또는 pip3 사용
pip install/uninstall 패키지_이름
pip3 intsall/uninstall 패키지_이름
1) datetime 모듈
date 클래스: 현재 날짜 or 지정된 날짜의 요일일 확인하거나 저장된 서식으로 년원일 정보 변환
time 클래스: 시간정보를 서식에 맞춰 문자열로 반환 (time모듈과 다르다!!!)
import datetime
d = date(2024, 7, 24)
print(d)
print(d.strftime("%Y년 %m월 %d일 요일: %A") #요일 'Wed'로 쓰고싶으면 '%a'
t = time(22, 8, 12)
print(t.strftime("%H시 %M분 %S초")

2) time 모듈
time 모듈에서는 일반적으로 1970년 1월 1일 00:00:00 UTC를 Epoch로 사용
이 시점을 기준으로 초 단위의 시간을 계산하여 time 모듈의 여러 함수들이 동작
import time
t1= time.time() # 작업 시작 시점의 현재 시간을 초 단위로 반환
sum = 0
maxNum = 10000000
for i in range (1, maxNum):
sum += i
t2 = time.time() # 작업이 끝난 시점의 현재 시간을 초 단위로 반환
print(f"1부터 {maxNum}까지 합하는 데 걸리는 시간은 {t2-t1}초")

✔ os.getcwd() : 현재 작업중인 디렉토리 경로 학인
✔ os.chdir() : 현재 작업중인 디렉토리 경로 변경
✔ os.mkdir() : 디렉토리 생성
✔ os.rmdir() : 디렉토리 삭제
✔ os.path.exists() : 경로/파일 존재 확인
✔ os.listdir(): 주어진 경로에 있는 모든 것을 리스트로 반환
✔ os.path.isdir(): 주어진 경로가 디렉토리인지 파악
✔ os.path.join(): 경로 결합
✔ os.path.isfile(): 주어진경로가 파일인지 파악
✔ os.path.getsize(): 파일 크기를 바이트로 반환
✔ os.remove(): 현재 작업 디렉트로에서 파일 삭제
✔ os.path.basename(): 파일 이름만 출력
?bc.txt: 3글자 파일명으로 끝나고 'bc.txt'로 끝나는 파일 찾기
*.txt: 확장자가 ".txt"인 모든 파일을 찾기
*: 현재 디렉토리의 모든 파일과 디렉토리를 찾기
!! glob은 파일 이름 매칭에 특화 !!
✔ os.path.join(file path , '와일드카드'): 파일 경로와 '와일드카드' 을 결합하여 검색 패턴 생성
#os와 glob 이용해서 파일 목록 출력하기
import os
import glob
files_path = r"/home/hyuna/work"
find_files = os.path.join(files_path,"*")
files = glob.glob(find_files)
for file in files:
print(file)

# my_package/utilities.py
def multiply_numbers(a, b):
return a * b
# main.py
from my_package.utilities import multiply_numbers
result = multiply_numbers(4, 5)
print(f"Result: {result}") # Result: 20
```python
import os
my_path = os.getcwd()
if os.path.isdir(my_path) == True:
print(my_path)
print(os.listdir(my_path))
else:
print("nothing")
>> /home/hyuna/work
>> ['abc.txt', 'divisors.py', 'Test.py', 'dice5.py', '__pycache__', 'testDivisors.py']
#divisors.py
def get_divisor(n):
divisor_list = []
for i in range(1, n+1):
if n % i == 0:
divisor_list.append(i)
print(f"{n}의 약수: {divisor_list}")
#testDivisors.py
import divisors
def main():
test_numbers = [10, 20, 30 ,40]
for num in test_numbers:
try:
divisor_numbers = divisors.get_divisor(num)
print(f"{num}의 약수: {divisor_numbers}")
except ValueError as e:
print(e)
if __name__ == "__main__":
main()

import os
import glob
def All_txt_list():
current_directory = os.getcwd()
pattern = os.path.join(current_directory, '*.txt')
txt_list = glob.glob(pattern)
if txt_list:
print('확장자가 ".txt"인 파일 목록: ')
for file in txt_list:
print(os.path.basename(file))
else:
print('확장자가 ".txt"인 파일이 없습니다')
if __name__ == "__main__":
All_txt_list()
