Python

[파이썬] 모듈 Ⅲ (내장함수 input, dir & 외장함수 glob, os, time, datetime, timedelta)

뉴라코 2024. 11. 11. 17:17
내장함수( 안에 들어있어서 import 하지 않아도 됨 )

 

- input함수 : 사용자 입력을 받는 함수

#input 사용자 입력을 받는 함수
language=input("무슨 언어를 좋아하세요?")
print("{0}은 아주 좋은 언어입니다.".format(language))

-dir함수: 어떤 객체를 넘겨줬을 때 그 객체가 어떤 변수와 함수를 가지고 있는지 표시해줌.

1)print(dir())

#dir 어떤 객체를 넘겨줬을 때 그 객체가 어떤 변수와 함수를 가지고 있는지 표시
print(dir())
import random #외장 함수
print(dir())
import pickle
print(dir())

: random 함수 추가/ pickl, random 함수 추가되어 터미널에 뜸.

 

2)print(dir(random))

1. import random 후 print(dir(random))입력하면 random 모듈내에서 쓸 수 있는 함수 주르륵 터미널에 뜸.

2. 그 내용은 import random 후 random. 하면 밑에 뜨는 함수들과 같음.

 

3)print(dir(1st)) 리스트형식

1st = [1,2,3]
print(dir(1st))

1. 결과는 리스트를 dir에 집어넣으면 리스트에서 쓸 수 있는 함수들이 뜬다.

 

4)print(dir(name)) 

name="james"
print(dir(name))

 

 

google에 list of python builtins 쳐서 필요한 내장함수 검색이 가능

https://docs.python.org/3/library/functions.html

 

Built-in Functions

The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.,,,, Built-in Functions,,, A, abs(), aiter(), all(), a...

docs.python.org


 

외장함수 (import가 꼭 필요함)

- glob : 경로 내의 폴더, 파일 목록을 조회할 수 있따 (윈도우의 dir 역할)

# glob:경로 내의 폴더/ 파일 목록 조회(윈도우의 dir 역할)
import glob
print(glob.glob("*.py")) #확장자가 py인 모든 파일
Terminal>>
['helloworld.py', 'practice.class.py', 'practice.py', 'practice2.py', 'practice3.py', 'question.py', 'theater_module.py', '예외처리.py']

 

- os: 운영체제에서 제공하는 기본 기능

1) 현재 디렉토리 표시하고 싶을 때 os.getcwd()

#os: 운영체제에서 제공하는 기본 기능
import os
print(os.getcwd()) #현재 디렉토리 표시
Terminal>>
C:\Users\USER\Desktop\python workspace

 

2) 폴더가 있는지 확인하고 싶을 때 os.path.exists(folder), 폴더를 만들고 싶을 때 os.makedirs(folder),  폴더를 삭제하고 싶을 때 os.rmdir(folder) -remove dir

import os
folder="sample.dir"

if os.path.exists(folder):
    print("이미 존재하는 폴더입니다.")
    os.rmdir(folder)
    print(folder,"폴더를 삭제하였습니다")
else:
    os.makedirs(folder) #폴더 생성
    print(folder,"폴더를 생성하였습니다.")
Terminal>>
sample.dir 폴더를 생성하였습니다.

Terminal2>>
이미 존재하는 폴더입니다.
sample.dir 폴더를 삭제하였습니다

 

3) glob와 같이 파일명들이 리스트로 적혀서 나오도록 할 때 os.listdir()

print(os.listdir())
Terminal>>
 ['helloworld.py', 'practice.class.py', 'practice.py', 'practice2.py', 'practice3.py', 'profile.pickle', 'question.py', 'theater_module.py', 'travel', '__pycache__', '예외처리.py']

 

- time :시간 관련 함수

import time
print(time.localtime())
print(time.strftime("%Y-%m-%d %H: %M: %S:"))
Terminal>>
time.struct_time(tm_year=2024, tm_mon=11, tm_mday=11, tm_hour=16, tm_min=48, tm_sec=58, tm_wday=0, tm_yday=316, tm_isdst=0)
2024-11-11 16: 48: 58:

 

-datetime

1)  time과 비슷하지만 더 간단한 형식으로 나오도록 할 때- datetime.date.today()

import datetime
print(datetime.date.today())
Terminal>>
2024-11-11

 

2) 두 날짜 사이의 간격이 필요할 때 datetime.timedelta(days=저장하고 싶은 날의 수)

#timedelta: 두 날짜 사이의 간격을 알려줌
import datetime
today=datetime.date.today() #오늘 날짜 저장
td= datetime.timedelta(days=100) # 100일 타임델타 저장
print("우리가 만난지 100일은",today+td) #오늘 날짜로부터 100일 뒤알려줌
Terminal>>
우리가 만난지 100일은 2025-02-19

 

google에 list of python modules쳐서 필요한 외장함수 검색이 가능

https://docs.python.org/3/py-modindex.html

 

Python Module Index — Python 3.13.0 documentation

numbers Numeric abstract base classes (Complex, Real, Integral, etc.).

docs.python.org


모듈 관련 문제

답변

#byme.py 모듈 파일
def sign(): #sign이라는 함수
    print("이 프로그램은 나도코딩에 의해 만들어졌습니다.")
    print("유튜브 :http://youtube.com")
    print("이메일: nadocoding@gmail")
#기존 파일에서
import byme
byme.sign()