반응형
Notice
Recent Posts
Recent Comments
Link
지구정복
[Python] 3/11 | Math모듈, Random모듈, 파일시스템, 파일입출력(우편번호검색) 본문
데이터 엔지니어링 정복/Python
[Python] 3/11 | Math모듈, Random모듈, 파일시스템, 파일입출력(우편번호검색)
noohhee 2021. 3. 11. 11:44728x90
반응형
복습
Java
프로그램언어기본(ECMAScript)
*문법
자료형
객체
변수
형변환
연산자
제어문
분기
반복
continue, break
*패키지 -라이브러리 제공에 기본단위
모듈
변수
함수
클래스
-import
-import ~ as ~
-from ~ import ~
-저장위치(PYTHONPATH)
. 현재 디렉터리
.. 상위 디렉터리
c:\python\python39\lib 기본제공패키지
c:\python\python39\site-package 추가 패키지
*pip 기능은 npm기능과 똑같다. (인터넷에서 바로 다운가능)/ setuptool
*기본
sys, os, subpress, webbrowser
Calendar, Time
1. Math 모듈 사용
더보기


올림 내림 버림
import math
#올림
print( math.ceil( 3.4 ) )
print( math.ceil( 3.5 ) )
print( math.ceil( 3.6 ) )
#내림
print( math.floor( 3.4 ) )
print( math.floor( 3.5 ) )
print( math.floor( 3.6 ) )
#버림
print( math.trunc( 3.4 ) )
print( math.trunc( 3.5 ) )
print( math.trunc( 3.6 ) )

지수 로그 연산
import math
#지수로그연산
print( math.pow( 2, 10 ) )
print( math.pow( 1.5, 3 ) )
print( math.sqrt( 2 ) )
print( math.exp( 2 ) )
print( math.log( math.e ) )

2. 랜덤 모듈 사용
더보기


random.seed() : 임의 숫자 생성기의 초기화 작업을 한다. 봉투에서 숫자를 꺼낸다고 하면 봉투를 흔드는 것을 의미
random.random() : 0.0 <= F < 1.0 사이의 임의의 float 숫자를 반환한다.
import random
# 0이상 1미만 실수반환
print( random.random() )
print( random.random() )
print( random.random() )
# 정수만 가져오기 1이상 10미만
print( int( random.random() * 10 ) )
print( random.randint( 0, 10 ) )

import random
#0에서 20 사이의 수 중 중복을 허용하지 않고 임의의 정수를 생성하기
print( random.sample( range( 20 ), 10 ) )

3. 파일시스템 사용하기
더보기




os.path
import os
#입력받은 경로를 절대 경로로 변환
print( os.path.abspath( 'tmp' ) )

os.path.getsize(path) : 입력받은 경로에 대한 바이트 단위의 파일크기를 반환
os.path.isfile( path ) : 경로가 파일인지 아닌지 검사한다. 파일인 경우 True를 반환하고 아니면 False 반환
glob
import glob
#해당경로에 모든 파일 출력 (절대경로 사용)
print( glob.glob( 'c:/python/*' ) )
#상대경로사용
print( glob.glob( './*' ) )

반복문을 통해 출력할 수 있다.
import glob
for file in glob.iglob( './*' ):
print( file )

tree
import glob, os.path
ndir = nfile = 0
def traverse( dir, depth ) :
global ndir, nfile
for obj in glob.glob( dir + '/*' ):
if depth == 0:
prefix = '|--'
else:
prefix = '|' + ' ' * depth + '|--'
if os.path.isdir(obj):
ndir += 1
print( prefix + os.path.basename(obj) )
traverse( obj, depth + 1 )
elif os.path.isfile(obj):
nfile += 1
print( prefix + os.path.basename( obj ) )
else:
print( prefix + 'unknown object :', obj )
if __name__ == '__main__':
traverse( '../..', 0 )
print( '\n', ndir, 'directories', nfile, 'files' )

4. 파일입출력
더보기










파일만들기 및 쓰기
이때 open( 파일명, 파일방식, 인코딩타입 )이다.
파일방식에는 w: 덮어쓰기, a: append방식 r: 파일 읽기 등이 있다.
#파일만들기
f = open( './test1.txt', 'w', encoding='utf-8' )
#파일내용 작성
f.write( 'Hello' )
f.write( 'Hello' )
f.write( 'Hello' )
f.close()


텍스트문서의 내용을 리스트형식으로 작성해보자.
#파일만들기
f = open( './test1.txt', 'w', encoding='utf-8' )
#파일내용 작성
lines = [
'Hello1\n',
'Hello2\n',
'Hello3\n',
]
f.writelines( lines )
print( '저장완료' )
f.close()

파일읽기
print( '시작' )
#파일읽기같은 경우 파일명이 잘못되면 에러가 나오므로 try except문을 이용한다.
try :
#파일 읽어들이기
f = open( './test1.txt', 'r', encoding = 'utf-8' )
while True:
line = f.readline()
if not line:
break
print( line, end='' )
f.close()
except FileNotFoundError as e:
print( 'error : ', e )
print( '끝' )

한줄씩읽지말고 한번에 다 읽기
print( '시작' )
#파일읽기같은 경우 파일명이 잘못되면 에러가 나오므로 try except문을 이용한다.
try :
#파일 읽어들이기
f = open( './test1.txt', 'r', encoding = 'utf-8' )
for line in f.readlines():
print( line, end='' )
f.close()
except FileNotFoundError as e:
print( 'error : ', e )
print( '끝' )

pickle 사용
리스트나 클래스 등을 저장할 때 사용한다.
import pickle
f = open( './pickle.dat', 'wb' )
colors = [ 'red', 'green', 'black' ]
pickle.dump( colors, f )
print( '저장완료' )
f.close()


저장한 .dat 파일 읽어들이기
import pickle
f = open( './pickle.dat', 'rb' )
colors = pickle.load( f )
print( colors )
f.close()

우편번호 검색기 만들기

f = open( './zipcode_all_utf8_type2.csv', 'r', encoding='utf-8' )
for line in f.readlines():
addresses = line.split( ',' )
if addresses[3].startswith( '신사' ):
print( line, end='' )
f.close()

728x90
반응형
'데이터 엔지니어링 정복 > Python' 카테고리의 다른 글
Comments