728x90
반응형
SMALL
Python 내장 함수 및 라이브러리를 어떻게 사용하는지, 파일 읽기, 쓰기 등 어떻게 하는지 살펴보자.

 

■ 파일 읽기, 쓰기 등 

# 파일 생성

f = open("d:/new.txt", 'w')    # 'r' : 읽기 모드    'w' : 쓰기 모드    'a' : 추가모드

for i in range(0, 10):    # 0~9까지 

    a = str(i) + "row\n"    # "\n"은 new line

    f.write(a)

f.close()    # close를 하지 않으면 파일이 열려 있는 상태이므로 꼭 close를 해줘야 한다. (파일 삭제가 되지 않음)

 

# 파일 읽기 (case1 ~ case3)

f = open("d:/new.txt" , 'r')

 

# case1 - line별로 담아서 출력

lines = f.readlines()

for line in lines:

    print(line)

 

# case2 - line 1개 출력

line = f.readline()

print(line)

 

# case3 - line 1개를 담아 1 글자씩 출력

lines = f.readline()

for line in lines:

    print(line)

 

f.close()

 

# read를 통하여 한번에 가져오기

f = open("d:/new.txt" , 'r')

a = f.read()

print(a)

f.close()

 

# 파일 내용 추가

f = open("d:/new.txt", 'a')

for i in range(10, 20):    # 10~19까지

    a = str(i) + "row"

    f.wirte(a)

f.close()

 

# f.close()를 사용하지 않고 파일 닫기

with open("d:/new.txt", 'r') as f:

    f.read()

 

■ Python 내장 함수

1. 절대값 : abs(-1.3) → 1

2. 모두 참이면 : all([1,2,3,4,5]) → True,    all([0,1,2,3,4]) → False

3. 하나라도 참이면 : any([0,1,2,3]) → True

4. 몫과 나머지 : divmod(9, 4) → (2, 1)

5. 정수 변환 : int(1.4) → 1

6. 문자열 변환 : str(7) → '7'

7. 리스트 변환 : list("12345") → ['1', '2', '3', '4', '5']

8. 튜플 변환 : tuple("12345") → ('1', '2', '3', '4', '5')

9. 길이 : len("12345") → 5

10. 최대값 : max([1, 2, 3]) → 3

11. 최소값 : min([1, 2, 3]) → 1

12. 아스키 값 : ord("a") → 97

13. 제곱 : pow(2, 3) → 8

14. 범위

   - list(range(5)) → [0, 1, 2, 3, 4]

   - list(range(5, 10)) → [5, 6, 7, 8, 9]

   - list(range(1, 10, 2)) → [1, 3, 5, 7, 9]

15. 반올림

   - round(0.7) → 1

   - round(0.5) → 0    # ※ 0이 되는 것 주의

   - round(0.555, 2) → 0.56

16. 정렬 : sorted([3, 2, 1]) → [1, 2, 3]

17. 합 : sum([2, 3, 5]) → 10

18. 자료형 가져오기 : type("a") → <class 'str'>

19. 자료형 묶음 : list(zip([1, 2], [3, 4])) → [(1, 3), (2, 4)]

 

■ 라이브러리(library) 사용

import os

import shutil

import glob

import tempfile

import time

import calendar

import webbrowser

 

os.environ    # 환경변수 출력

os.chdir("d:/")    # 디렉터리 변경

os.getcwd()    # 디렉터리 위치

 

shutil.copy("d:/new.txt", "d:/new1.txt")    # new.txt을 new1.txt로 복사, 파일이 있으면 덮어씀

 

glob.glob("d:/new*")    # d드라이 안에 new로 시작하는 파일 찾기

 

file = tempfile.mkstemp()    # 중복되지 않은 임시 파일을 만듦, 결과값은 파일 경로

# 임시로 파일을 만들고, close()로 파일을 삭제한다.

f = tempfile.TemporaryFile()

f.close()

 

time.time()    # 1970.01.01 00:00:00 기준으로 지난 시간을 초단위로 반환 (UTC 기준)

time.localtime(time.time())    # 년, 월, 일, 시, 분, 초로 반환

time.asctime(time.localtime(time.time()))    # 날짜 정렬

time.ctime()    # 오늘날짜 반환

time.strftime('%a', time.localtime())    # 요일 반환 (형태 : 'Sun') - 날짜 포맷 코드는 아래 표 참고

 

calendar.calendar(2023)    # 2023년 달력 (한 줄 표시)

calendar.prcal(2023)    # 2023년 달력 (달력처럼 표시)

calendar.prmonth(2023, 5)    # 2023년 5월 달력

calendar.weekday(2023, 5, 21)    # 6 반환 (월요일 : 0 ~ 일요일 : 6)

calendar.monthrange(2023, 5)    # (0, 31) 반환 : 0은 5월 시작일의 요일, 31은 5월의 마지막 날

 

webbrowser.open("http://200-rush.tistory.com")    # 해당 url open

 

■ 날짜 포맷 코드

코드 표현 (설명) 코드 표현 (설명) 코드 표현 (설명)
%a 'Sun' (약자) %I '02' (12시 기준 시간) %w '0' (요일)
%A 'Sunday' %j '141' (1년 중 누적날짜) %W '20' (1년 중 누적 주 - 월요일 시작)
%b 'May' (약자) %m '05' (월) %x '05/21/23/
%B 'May' %M '08' (분) %X '14:13:39'
%c Sun May 21 14:04:38 2023 %p 'AM' or 'PM' %Y '2023'
%d '21' (날짜) %S '23' (초) %Z '대한민국 표준시'
%H '14' (24시 기준 시간) %U '21' (1년 중 누적 주 - 일요일 시작) %y '23' (yy만 표시)

- 날짜 포맷 코드 응용 : time.strftime('%Y%m%d', time.localtime()) → '20230521'

728x90
반응형
LIST

+ Recent posts