본문 바로가기

2013/07

pickle 리스트나 클래스를 파일에 저장할 때 사용바이너리로 읽어야 한다>>> colors = ['red', 'green', 'black']>>> colors['red', 'green', 'black'] pickle 모듈의 dump() 함수를 이용해 colors를 파일에 저장>>> import pickle>>> f = open('colors', 'wb')>>> pickle.dump(colors, f)>>> f.close() colors를 삭제한 후 load() 함수를 이용해 파이썬 객체를 읽음>>> del colors>>> colorsTraceback (most recent call last): File "", line 1, in colorsNameError: name 'colors' is not defined>>.. 더보기
파일 입출력 파일 객체 = open(file, mode)file 파일명mode r: 읽기모드(디폴트)w: 쓰기모드a: 쓰기 + 이어쓰기 모드+: 읽기 + 쓰기모드b: 바이너리 모드t: 텍스트모드(디폴트)>>> f = open('text.txt','w')>>> f.write('plow deep\nwhile sluggards sleep')31>>> f.close() 바이너리 모드로 mp3 파일 복사하기>>> f = open('good2.mp3', 'wb')>>> f.write(open('good.mp3','rb').read())14412106>>> f.close() readline() 한 줄씩 읽음readlines() 줄 단위로 잘라서 리스트를 반환seek() 사용자가 원하는 위치로 파일 포인터 이동tell() 현재 파.. 더보기
포맷팅 {}안의 값은 숫자로 표현format 인자의 인덱스로 사용>>> print("{0} is {1}".format("apple", "red"))apple is red>>> print("{0} is {1} or {2}".format("apple", "red", "green"))apple is red or green format의 인자로 키와 값을 지정해 사용 가능>>> print("{item} is {color}".format(item="apple", color="red"))apple is red 사전을 입력으로 받는 경우>>> dic = {"item":"apple", "color":"red"}>>> print("{0[item]} is {0[color]}".format(dic))apple is red0[ite.. 더보기
출력 인자가 여러 개 들어가면 공백으로 구분해서 출력+ 연산자를 이용하면 공백이 없음>>> print(x, 'test')0.2 test>>> print(a + 'this is test')'hello\n'this is test 구분자(sep), 끝라인(end), 출력(file)을 지정할 수 있음>>> import sys>>> print("welcome to", "python", sep="~", end="!", file=sys.stderr) >> f = open('test.txt', 'w')>>> print('file write', file = f)>>> f.close() 화면에 출력할 때 중을 맞추거나 정렬할 때string 객체에서 제공되는 함수를 이용print() 함수에서 제공하는 format 이용>>> fo.. 더보기
repr(), str(), ascii() str은 실제 객체의 값과 다를 수가 있습니다. eval(repr(obj))는 실제 obj와 동일한 값을 생성할 수 있어야 합니다. 하지만 eval(str(obj))는 실제 obj와 동일한 값이 아니거나, 오류를 내는 경우가 있을 수 있습니다.eval()는 string형식으로 받은 문자열을 그대로 실행해준다.ascii()은 아스키에 해당하는 문자열에 대해서 정확히 동일한 값을 반환한다.다만 아스키 이외의 값에 대해서는 백슬래시를 사용한 유니코드값을 반환한다.[출처] Python, str(), repr(), ascii(),eval()|작성자 Youngjae[출처] Python, str(), repr(), ascii(),eval()|작성자 Youngjae>>> f = 0.3 >>> f 0.2999999999.. 더보기
assert 구문 인자로 받은 조건식이 거짓인 경우 AssertError가 발생assert , def foo(x): assert type(x) == int, "Input value must be integer" return x * 10 ret = foo("a") print(ret) Traceback (most recent call last): File "/Users/MGP/Documents/workspace/Python/src/testmodule/__init__.py", line 5, in ret = foo("a") File "/Users/MGP/Documents/workspace/Python/src/testmodule/__init__.py", line 2, in foo assert type(x) == int, "Inpu.. 더보기
raise 구문 의도적으로 예외 발생 raise[Exception] 해당 예외를 발생raise[Exception(data)] 예외 발생 시 관련 데이터를 전달raise 발생된 예외를 상위로 전달 내장 예외 발생 예제>>> def RaiseErrorFunc():raise NameError>>> try:RaiseErrorFunc()except:print("NameError is Catched")NameError is Catched 내장 예외 전달 예제>>> def RaiseErrorFunc():raise NameError("Parameter of NameError")>>> def PropagateError():try:RaiseErrorFunc()except:print("before")raise>>> PropagateErro.. 더보기
사용자정의 예외 >>> class NegativeDivisionError(Exception): >> def PositiveDivide(a, b):if(b > try:ret = PositiveDivide(10, -3)print('10 / 3 = {0}'.format(ret))except NegativeDivisionError as e:print("Error - Second argument of PositiveDivide is ", e.value)except ZeroDivisionError as e:print("Error - ", e.args[0])except:print("Unexpected exception") Error - Second argument o.. 더보기
예외처리 try 블록예외가 예상되는 부분에 작성 except 블록에외발생 시 처리를 담당하는 부분 else 블록예외가 발생하지 않은 경우 수행 finally 블록예외발생과 상관 없이 수행 >>> def divide(a, b):return a/b>>> try:c = divide(5, 0)except:print("Exception is occured!!")Exception is occured!! 처리할 예외를 명시 할 수 있다.>>> def divide(a, b):return a/b>>> try:c = divide(5, 'string')except ZeroDivisionError:print('ZeroDivisonError.')except TypeError:print("TypeError")except:print("I .. 더보기
JAVA에서 높이 넓이 설정 m_viewFlipper = (ViewFlipper)findViewById(R.id.viewFlipper1);LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 0);m_viewFlipper.setLayoutParams(lp); 더보기