프로그래밍 언어/Python

[개요] 파이썬 퀵 가이드(Quick Guide)

투칼론 2016. 3. 10. 23:35
반응형

파이썬 개요:

파이썬은 프로그래밍 언어, 인터프리터 방식, 대화적인언어이고 객체 지향 스크립트 언어이다.

  • Python is Interpreted (인터프리터 방식)

  • Python is Interactive (대화 형식)

  • Python is Object-Oriented (객체 지향)

  • Python is Beginner's Language (쉬운 언어)

파이썬은 귀도 반 로섬(Guido van Rossum)이 1980년대 말부터 1990년대 초에 네덜란드 수학 & 컴퓨터과학 국가연구기관에서 개발하였다.  

파이썬의 주요 특징은 아래와 같다. :

  • Easy-to-learn (배우기 용이성)

  • Easy-to-read (가독성)

  • Easy-to-maintain (유지보수 편의성)

  • A broad standard library (다양한 표준 라이브러리)

  • Interactive Mode (대화형 모드)

  • Portable (이식성)

  • Extendable (확대성)

  • Databases (데이타베이스)

  • GUI Programming (GUI 프로그래밍)

  • Scalable (확장성)


파이썬 시작하기:

가장 최근 소스코드, 바이너리, 문서, 새소식 등은 아래 파이썬 공식 웹사이트에 있다:

파이썬 공식  : http://www.python.org/

파이썬 문서는 아래 사이트에서 다운로드 할 수 있다. HTML, PDF와 PostScript 형식으로 제공한다. 

파이썬 문서 사이트 : www.python.org/doc/


첫번째 파이썬 프로그램:


대화형 모드 프로그래밍:

파라미터로 스크립트 파일을 전달하지 않으면, 인터프리터를 호출하고, 아래와 같은 파이썬 프롬프트를 보여준다:

root# python
Python 2.5 (r25:51908, Nov  6 2007, 16:54:01)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more info.
>>>

파이썬 프롬프트(>>>) 이어서 텍스트를 입력하고, 엔터키를 누른다:

>>> print "Hello, Python!";

아래와 같은 결과가 나올 것이다.:

Hello, Python!


파이썬 식별자(Identifiers):

파이썬 식별자는 변수, 함수, 클래스, 모듈 또는 다른 객체를 식별한다. 식별자는 A부 Z까지 문자 또는 a부터 z 또는 언더스코어(_)로 시작하고, 다음에는 문자들, 언더스코어(_)와 숫자(0-9)이 온다.

파이썬은 @, $, % 등 문장부호(punctuation)는 식별자에 사용하지 않는다. 파이썬은 대.소문자 구별하는 프로그래밍 언어이다. 즉 Manpower와 manpower는 파이썬에서는 다르게 식별된다.

파이썬 식별자의 명명규칙은 아래와 같다. 

  • 클래스명은 시작하는 대문자를 제외하고, 모두 소문자이다.

  • 단일 언더스코어(_)로 시작하는 식별자는 프라이빗(private)이라는 의미이다.

  • 두개 언더스코어(__)로 시작하는 식별자는 강한 프라이빗(strong private)이라는 의미이다.

  • 식별자가 두개 언더스코어(__)로 끝나는 식별자는 언어에 의해 정의된 특별한 이름을 의미한다. 


예약어(Reserved Words):

다음은 파이썬 예약어이다. 이 예약어들은 상수(constant) 또는 다른 식별자로 사용할 수 없다,

andexecnot
assertfinallyor
breakforpass
classfromprint
continueglobalraise
defifreturn
delimporttry
elifinwhile
elseiswith
exceptlambdayield


라인과 들여쓰기(Lines and Indentation):

파이썬을 배울때 프로그래머가 처음 알게되는 규칙 중 하나는 파이썬은 클래스와 함수 선언 또는 제어문에 중괄호({})가 없다는 것이다. 대신에 코드 블록은 엄격한 라인과 들여쓰기에 영향을 받는다.

들여쓰기에서 공백(space) 수는 가변적이지만, 블록안에 모든 문장(statement)는 반드시 들여쓰기를 위한 공백 갯수가 같아야한다. 아래 블록들은 좋은 예이다.  

if True:
    print "True"
else:
  print "False"

하지만, 아래 예제에서 두번째 블록때문에 오류가 발생한다.

if True:
    print "Answer"
    print "True"
else:
    print "Answer"
  print "False"


멀티라인 문장(Multi-Line Statements):

파이썬에서 문장은 보통 새로운 라인으로 구별한다. 하지만 다음 라인이 계속된 문장으로 인식하기 위해서 라인 연결 문자(\)를 사용한다. 예시:

total = item_one + \
        item_two + \
        item_three

[], {} 또는 () 괄호를 포함한 문장은 라인 연결 문자(\)가 필요하지 않다. 예시:

days = ['Monday', 'Tuesday', 'Wednesday',
             'Thursday', 'Friday']


파이썬에서 인용부호(Quotation):

파이썬은 single ('), double (")과 triple (''' or """) 인용부호로 문자열을 나타낸다. 물론 시작과 끝이 동일한 인용부호이어야 한다. 

triple 인용부호(''' or """)는 멀티라인에 걸쳐져 있는 문자열로 사용된다. 아래 예시는 모두 적절한 사용이다:

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""


파이썬에서 주석처리(Comments):

해쉬 부호 (#)는 주석처리를 시작한다. # 뒤에오는 라인 끝까지의 모든 문자열은 주석처리되고 인터프리터는 무시한다.

#!/usr/bin/python

# First comment
print "Hello, Python!";  # second comment

위는 아래 결과가 나온다.:

Hello, Python!

주석은 문장 또는 표현식 뒤에 같은 라린에 올 수 있다:

name = "Madisetti" # This is again comment

멀티라인 주석처리는 아래와 같다. 큰따움표 3개를 적는다:

"""

This is a comment. This is a comment, too. This is a comment, too. I said that already.

"""


공백 라인 사용(Using Blank Lines):

공백문자로 이루어진 라인 또는 주석만 있는 라인은 모두 공백 라인으로 인식되어 파이썬은 무시하고 어떠한 처리를 하지 않는다.

대화형 인터프리터 세션에서, 멀티라인 문장을 종료시키기 위해서는 공백라인을 입력해야 한다. 


한 라인에 여러 문장:

세미콜론 (;)은 한 라인에서 새로운 코드블록 시작이 아닌 여러 문장들을 오게한다. 

여기에 세미콜론이 있는 간단한 예제코드가 있다:

import sys; x = 'foo'; sys.stdout.write(x + '\n')


스윗(Suites) - 복수개 문장 그룹:

파이썬에서 각 문장들의 그룹으로 코드블록을 만드는데 이를 스윗(suites)라고 한다.

if, while, def와 class와 같은 혼합 또는 복잡(Compound or complex) 문장들은 헤더 라인과 스윗(suite)이 필요하다.

헤더 라인은 키워드와 시작되고 콜론 (:)으로 끝나고, 뒤에 스윗(suite)이라는 한 라인 또는 여러 라인이 온다.

예시:

if expression : 
   suite
elif expression : 
   suite 
else : 
   suite


파이썬 - 변수 유형:

변수는 값을 저장하기 위해 예약된 메모리 영역에 위치된다. 변수를 생성할 때, 메모리의 일부 영역을 예약한다는 뜻이다. 

변수의 데이타 유형에 따라 인터프리터는 메모리를 할당하고 할당된 메모리에 어떤 값을 저장할지를 결정한다. 그러므로 그 변수들에 다른 데이타 유형 정수값, 소수값 또는 문자 등을 저장한다.


변수에 값 부여(Assigning Values to Variables):

= 연산자의 왼쪽 피연산자는 변수이름이고, 오른쪽 피연산자는 값이다. 예시: 

counter = 100          # An integer assignment
miles   = 1000.0       # A floating point
name    = "John"       # A string

print counter
print miles
print name


표준 데이타 유형:

파이썬은 5가지 표준 데이타 유형:

  • Numbers

  • String

  • List

  • Tuple

  • Dictionary


Python Numbers:

숫자 객체는 변수에 값을 넣을때(assign) 생성된다. 예시:

var1 = 1
var2 = 10

파이썬은 4개 숫자형 유형을 지원한다:

  • int (signed integers)

  • long (long integers [8진수와 16진수 포함)

  • float (floating point real values)

  • complex (complex numbers)

숫자형에 대한 예시는 아래와 같다:

intlongfloatcomplex
1051924361L0.03.14j
100-0x19323L15.2045.j
-7860122L-21.99.322e-36j
0800xDEFABCECBDAECBFBAEL32.3+e18.876j
-0490535633629843L-90.-.6545+0J
-0x260-052318172735L-32.54e1003e+26J
0x69-4721885298529L70.2-E124.53e-7j


파이썬 문자열(Python Strings):

파이썬에서 문자열은 인용부호 사이의 연속적인 문자집합이다.

예시:

str = 'Hello World!'

print str          # Prints complete string
print str[0]       # Prints first character of the string
print str[2:5]     # Prints characters starting from 3rd to 6th
print str[2:]      # Prints string starting from 3rd character
print str * 2      # Prints string two times
print str + "TEST" # Prints concatenated string


파이썬 리스트(Python Lists):

리스트는 파이썬 혼합형 데이타 유형에서 가장 유용하다. 리스트는 콤마(,)로 구분되고, 대괄호 ([])로 시작과 끝이 닫힌다.

#!/usr/bin/python

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print list          # Prints complete list
print list[0]       # Prints first element of the list
print list[1:3]     # Prints elements starting from 2nd to 4th
print list[2:]      # Prints elements starting from 3rd element
print tinylist * 2  # Prints list two times
print list + tinylist # Prints concatenated lists


파이썬 튜플(Python Tuples):

튜플은 리스트와 유사한 시퀀스 데이타 유형이다. 튜플은 콤마(,)로 값이 구분되어진다. 리스트와는 다르게 괄호(())로 닫는다.

튜플은 읽기 전용(read-only) 리스트이라고 생가하면된다.

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')

print tuple           # Prints complete list
print tuple[0]        # Prints first element of the list
print tuple[1:3]      # Prints elements starting from 2nd to 4th
print tuple[2:]       # Prints elements starting from 3rd element
print tinytuple * 2   # Prints list two times
print tuple + tinytuple # Prints concatenated lists


파이썬 딕셔너리(Python Dictionary):

파이썬 딕셔너리는 해쉬 테이블 유형이다. 키-값 쌍으로 구성된다.

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one']       # Prints value for 'one' key
print dict[2]           # Prints value for 2 key
print tinydict          # Prints complete dictionary
print tinydict.keys()   # Prints all the keys
print tinydict.values() # Prints all the values


파이썬 기본 연산자(Basic Operators):

OperatorDescriptionExample
+

더하기 - 연산자의 양쪽 피연산자 더한다.

a + b will give 30
-

빼기 - 왼쪽 피연산자에서 오른쪽 피연산자을 뺀다.

a - b will give -10
*

곱하기 - 양쪽 피연산자를 곱한다.

a * b will give 200
/

나누기 - 오른쪽 피연산자로 왼쪽 피연산자를 나눈다.

b / a will give 2
%

나머지 - 오른쪽 피연산자로 왼쪽 피연산자를 나눈 나머지

b % a will give 0
**지수 - 왼쪽 피연산자를 오른쪽 피연산자 만큼 거듭제곱a**b will give 10 to the power 20
//Floor Division - 나누고, 몫. 소수점이하는 버린다.9//2 is equal to 4 and 9.0//2.0 is equal to 4.0
==

두 피연산자가 같은지 다른지 비교한다. 같다면 참(true) 이다.

(a == b) is not true.
!=두 피연산자가 같은지 다른지 비교한다. 다르면 참(true) 이다.(a != b) is true.
<>두 피연산자가 같은지 다른지 비교한다. 다르면 참(true) 이다.(a <> b) is true. This is similar to != operator.
>

왼쪽 피연산자가 오른쪽 값보다 크다면 참(true)이다.

(a > b) is not true.
<

왼쪽 피연산자가 오른쪽 피연산자보다 작다면 참(true)이다.

(a < b) is true.
>=왼쪽 피연산자가 오른쪽 피연산자보다 크거나 같다면 참(true)이다.(a >= b) is not true.
<=왼쪽 피연산자가 오른쪽 피연산자보다 작거나 같다면 참(true)이다.(a <= b) is true.
=

간단한 할당 연산, 오른쪽 피연산자를 왼쪽 변수에 할당.

c = a + b will assigne value of a + b into c
+=

왼쪽 피연산자와 오른쪽 피연산자를 더한 후에 왼쪽에 할당.

c += a is equivalent to c = c + a
-=

왼쪽 피연산자에서 오른쪽 피연산자를 뺀 후에 왼쪽 피연산자에 할당.

c -= a is equivalent to c = c - a
*=

왼쪽 피연산자와 오른쪽 피연산자를 곱 후에 왼쪽 피연산자에 할당.

c *= a is equivalent to c = c * a
/=왼쪽 피연산자를 오른쪽 피연산자로 나눈 후에 왼쪽 피연산자에 할당.c /= a is equivalent to c = c / a
%=왼쪽 피연산자를 오른쪽 피연산자로 나눈 나머지값을 왼쪽 피연산자에 할당.c %= a is equivalent to c = c % a
**=왼쪽 피연산자를 오른쪽 피연산자로 거듭제곱 후에 왼쪽 피연산자에 할당.c **= a is equivalent to c = c ** a
//=

왼쪽 피연산자를 오른쪽 피연산자로 나눈 후 몫(floor division)을 왼쪽 피연산자에 할당.

c //= a is equivalent to c = c // a
&

이진 AND 연산자. 

(a & b) will give 12 which is 0000 1100
|이진 OR 연산자. (a | b) will give 61 which is 0011 1101
^이진 XOR 연산자. (a ^ b) will give 49 which is 0011 0001
~

보수 연산자. 이진형식에서 비트를 바꿈.

(~a ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number.
<<왼쪽 시프트 연산자. 오른쪽 지정된 숫자만큼 왼쪽으로 시프트 함.a << 2 will give 240 which is 1111 0000
>>왼쪽 시프트 연산자. 오른쪽 지정된 숫자만큼 오른쪽으로 시프트 함.a >> 2 will give 15 which is 0000 1111
and

논리 AND 연산자. 두 피연산자가 모두 참일때 조건은 참.

(a and b) is true.
or

논리 OR 연산자. 두 피연산자가 한개라도 참일때 조건은 참.

(a or b) is true.
not

논리 NOT 연산자. 조건 상태를 반대로 함. 예로 조건이 참이면 거짓이됨.

not(a && b) is false.
in

변수가 in 다음 연속 항목에 있으면, 참 없으면 거짓임.

x in y, here in results in a 1 if x is a member of sequence y.
not in

변수가 in 다음 연속 항목에 있으면, 거짓 있으면 거짓임. in과 반대임.

x not in y, here not in results in a 1 if x is not a member of sequence y.
is

동일한 객체를 가리키면 참, 그렇지 않으면 거짓

x is y, here is results in 1 if id(x) equals id(y).
is not동일한 객체를 가리키지 않으면 참, 가리키면 거짓 x is not y, here is not results in 1 if id(x) is not equal to id(y).


파이썬 연산자 우선순위

아래 표는 연산 순위를 보여준다. 위에 있는 연산자부터 우선 계산된다.

OperatorDescription
**Exponentiation (raise to the power)
~ + -Ccomplement, unary plus and minus (method names for the last two are +@ and -@)
* / % //Multiply, divide, modulo and floor division
+ -Addition and subtraction
>> <<Right and left bitwise shift
&Bitwise 'AND'
^ |Bitwise exclusive `OR' and regular `OR'
<= < > >=Comparison operators
<> == !=Equality operators
= %= /= //= -= += |= &= >>= <<= *= **=Assignment operators
is is notIdentity operators
in not inMembership operators
note or andLogical operators


if 문장:

if 문장의 문법은:

if expression:
   statement(s)


else 문장:

if...else 문장의 문법은:

if expression:
   statement(s)
else:
   statement(s)


elif 문장:

if...elif 문장의 문법은:

if expression1:
   statement(s)
elif expression2:
   statement(s)
elif expression3:
   statement(s)
else:
   statement(s)


중첩Nested if...elif...else Construct

중첩된 if...elif...else construct 은:

if expression1:
   statement(s)
   if expression2:
      statement(s)
   elif expression3:
      statement(s)
   else
      statement(s)
elif expression4:
   statement(s)
else:
   statement(s)


while 루프:

while 루프의 문법은:

while expression:
   statement(s)


무한반복문(Infinite Loops):

while 루프를 사용할때에는 무한반복에 빠지지 않도록 조심해야 한다. 절대 끝나지 않는 반복을 무한반복문이라고 한다. 

무한루프는 클라이언트/서버 프로그래밍에서 클라이언트가 요청을 계속적으로 처리하는 서버 프로그램에서 유용하게 사용된다.


한 문장 스윗(Single Statement Suites):

if 문장 문법처럼 while 문에서도 한 라인의 문장이 온다면, 같은 라인에 작성하면 된다.

아래는 한 라인으로 된 while 구문임:

while expression : statement


for 반복문:

for 반복문 문법은:

for iterating_var in sequence:
   statements(s)


연속적인 인덱스 반복문:

각 항목별 반복적인 문법은 인덱스 오프셋(offset)을 이용한다:

fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
   print 'Current fruit :', fruits[index]

print "Good bye!"


break 문:

break 문장은 현재 반복을 종료시키고, 다음 문장을 실행한다. 기존 C에서 break와 비슷하다.

일반적으로 break 사용은 외부 조건에 의해 반복을 빠져나갈 때 사용된다. break 문장은 while과 for 구문에서 사용된다.

for letter in 'Python':     # First Example
   if letter == 'h':
      break
   print 'Current Letter :', letter
  
var = 10                           # Second Example
while var > 0:              
   print 'Current variable value :', var
   var = var -1
   if var == 5:
      break

print "Good bye!"


continue 문:

continue 문은 while 반복문에서 처음으로 제어를 넘겨준다. 아래 남아있는 문장은 무시하고, 반복문 맨 처음부터 다시 시작한다.

continue 문은 while과 for 문에서 사용된다.

for letter in 'Python':     # First Example
   if letter == 'h':
      continue
   print 'Current Letter :', letter

var = 10                    # Second Example
while var > 0:              
   print 'Current variable value :', var
   var = var -1
   if var == 5:
      continue

print "Good bye!"


반복문과 사용되는 else문:

파이썬은 반복문과 함께 else를 사용할 수 있다.

  • else 문이 for 반복문과 함께 사용되면, else 문은 반복문 끝났을때 수행된다.

  • else 문이 while 반복문과 함께 사용되면, else 문은 조건이 거짓이 될때 수행된다.


pass 문:

pass문은 어떤 명령 또는 코드를 실행하지 않고자 할때 필요하다.

pass문은 널(null) 연산; 실행할 때 아무일도 하지 않는다. pass는 작성이 완료되지 않아 그냥 수행시키고 싶지 않은 블록이 있을 때 유용하게 사용할 수 있다.

#!/usr/bin/python

for letter in 'Python': 
   if letter == 'h':
      pass
      print 'This is pass block'
   print 'Current Letter :', letter

print "Good bye!"


함수 선언

필요한 함수화를 정의할 때 함수 선언할 수 있다. 아래는 함수를 선언하는 간단한 룰이다:

  • 함수는 키워드 def로 시작하고 함수면과 괄호( ( ) )가 온다.

  • 어떤 입력 파라미터 또는 인자는 괄호안에 있다. 괄호안에 파라미터를 정의할 수 있다.

  • 함수의 첫번째 문장은 선택적 문장이 올 수 있다 - 함수의 문서 문자열 또는 docstring.

  • 모든 함수 안에 코드 블록은 콜론(:)으로 시작되고 정렬이 되어있다.

  • 리턴(return) 문은 함수를 빠져나가고, 선택적으로 호출자에게 expression을 돌려준다. 인자없는 리턴 문은 리턴 None과 같다.

문법:

def functionname( parameters ):
   "function_docstring"
   function_suite
   return [expression]

기본적으로 파라미터는 위치가 중요하기 때문에 정의된 순서로 처리해야 한다.

예시:

파이썬 함수의 간단한 예제이다. 이 함수는 문자열을 입력 파라미터로 받아 표준출력에 문자열을 출력하는 간단한 예제이다.

def printme( str ):
   "This prints a passed string into this function"
   print str
   return


함수 호출

함수 선언은 함수안에 포함되고 코드 블록 구조에 있는 이름을 정의한다.

기본 함수 구조가 끝나자마자 다른 함수 호출 또는 파이썬 프롬프트에서 직접 호출 가능하다.

아래는 printme()이라는 함수를 호출하는 예제이다:

#!/usr/bin/python

# Function definition is here
def printme( str ):
   "This prints a passed string into this function"
   print str;
   return;

# Now you can call printme function
printme("I'm first call to user defined function!");
printme("Again second call to the same function");

아래와 같은 결과가 출력된다:

I'm first call to user defined function!
Again second call to the same function


파이썬 - 모듈(Python - Modules):

모듈은 파이썬 코드를 논리적으로 분리하도록 한다. 관련된 코드를 그룹핑하는 것은 코드를 이해하고 사용하는 것을 쉽게 한다.

모듈은 바인드(bind)하고 레퍼런스(reference)할 수 있는 파이썬 객체이다. 

간단히 모듈은 파이썬 코드를 담고 있는 파일이다. 모듈은 함수, 클래스와 변수를 정의한다. 모듈은 토한 실행가능한(runnable)코드를 포함할 수 있다.

예시:

파이썬 코드에서 모듈명 aname은 aname.py로 존대한다. 아래는 hello.py라는 간단한 모듈 예제이다.

def print_func( par ):
   print "Hello : ", par
   return


import 문:

파이썬 소스에서 다른 모듈 소스 파일을 import 문을 통해 사용할 수 있다. import는 아래와 같은 문법을 가지고 있다:

import module1[, module2[,... moduleN]

인터프리터가 import문을 처리할때, 모듈이 검색 경로에 있으면 import한다. 검색 경로는 모듈을 import 하기 전 검색하는 디렉토리 목록이다.

예시:

hello.py 모듈을 임포트하기 위해, 스크립트 맨 위에 다음과 같은 명령어를 넣는다:

#!/usr/bin/python

# Import module hello
import hello

# Now you can call defined function that module as follows
hello.print_func("Zara")

위 문장은 아래와 같은 결과를 보여준다:

Hello : Zara

모듈은 import 횟수와 상관없이 한번 로드된다. 이는 여러번 임포트 할때, 반복적인 수행을 방지한다.


파일 열기와 닫기:

open 함수:

파일을 읽고 쓰기 위해서는 파이썬 빌드인 open() 함수를 사용하여 파일을 우선 열어야 한다. 이 함수는 파일과 관련된 다른 지원 메소드를 사용할 수 있도록 파일 객체를 생성한다.

문법:

file object = open(file_name [, access_mode][, buffering])

파라미터 상세 설명:

  • file_name: file_name 인자는 접근하기를 원하는 파일을 의미하는 문자열이다.

  • access_mode: access_mode는 파일을 읽기, 쓰기, 추가(append) 모드를 결정한다. 모드값으로 가능한 값은 아래 표에서 설명한다. 선택적인 파라미터와 기본 파일 접근 모드는 읽기(r)이다.

  • buffering: 버퍼링(buffering) 값이 0으로 설정되어 있으면, 버퍼링을 하지 않는다. 버퍼링 값이 1이면, 파일 접근 시에 라인 버퍼링을 한다. 1보다 큰 값을 설정하면, 지정된 버퍼 크기만큼 버퍼링이 수행된다. 이 값은 선택적이다.

파일 열때 사용하는 모드 목록:

ModesDescription
r

읽기 전용. 파일 포인터는 파일 맨 처음에 위치한다. 기본 모드임.

rb

바이너리 형식의 읽기 전용. 파일 포인터는 파일 맨 처음에 위치한다. 기본 모드임.

r+

읽기와 쓰기 모드. 파일 포인터는 파일 맨 처음에 위치한다.

rb+

이너리 형식에서 읽기와 쓰기 모드.  파일 포인터는 파일 맨 처음에 위치한다

w

쓰기 전용. 파일이 존재하면, 겹쳐쓰고, 존재하지 않으면 새로 생성한다.

wb

바이너리 형식의 쓰기 전용. 파일이 존재하면, 겹쳐쓰고, 존재하지 않으면 새로 생성한다.

w+

읽기와 쓰기.  파일이 존재하면, 겹쳐쓰고, 존재하지 않으면 새로 생성한다.

wb+

바이너리 형식에서 읽기와 쓰기파일이 존재하면, 겹쳐쓰고, 존재하지 않으면 새로 생성한다

a

추가 모드. 파일이 존재한다면 포인터가 파일 맨뒤에 위치함. 추가(append)모드에서 파일이 존재하지 않으면 파일은 새로 생성된다.

ab

바이너리 형식의 추가 모드. 파일이 존재한다면 포인터가 파일 맨뒤에 위치함. 추가(append)모드에서 파일이 존재하지 않으면 파일은 새로 생성된다.

a+

추가와 읽기 모드. 파일이 존재한다면 포인터가 파일 맨뒤에 위치함. 추가(append)모드에서 파일이 존재하지 않으면 읽기와 쓰기 모드의 파일이 새로 생성된다.

ab+

바이너리 형식의 추가와 읽기 모드. 파일이 존재한다면 포인터가 파일 맨뒤에 위치함. 추가(append)모드에서 파일이 존재하지 않으면 읽기와 쓰기 모드의 파일이 새로 생성된다. 

파일 객체 속성:

파일을 열어 파일 객체를 통해 파일 관련 다양한 정보를 얻을 수 있다.

파일 객체와 관련된 속성 목록:

AttributeDescription
file.closed

파일이 닫혀있으면 참(true)을 돌려주고, 아니면 거짓(false)을 돌려준다.

file.mode

열려있는 파일의 접근 모드를 돌려준다.

file.name

파일명을 돌려준다.

file.softspace

print문을 사용할때 명시적으로 공백문자가 필요한 경우에는 거짓, 필요 없는 경우(자동으로 공백문자 넣어줌)에는 참을 돌려준다.

close() 메소드:

close() 메소드는 버퍼에서 쓰여지지 않는 정보를 flush하고, 파일 객체를 닫는다. 닫은 후에는 더이상 파일에 쓸 수 없다.

fileObject.close();


파일 읽기와 쓰기:

write() 메소드:

문법:

fileObject.write(string);


read() 메소드:

Syntax:

fileObject.read([count]);


파일 위치(File Positions):

tell() 메소드는 파일에서 현재 포인터 위치를 알려준다. 그 위치가 파일의 읽고 쓰기 할때 시작점이 된다.

seek(offset[, from]) 메소드는 현재 파일 포인터를 변경한다. offset 인자는 옮기고자하는 바이트 수를 의미한다. from 인자는 바이트 만큼 이동될 기준 위치를 의미한다.

from 이 0이라는 의미는 기준 위치가 파일 처음이라는 것이고, 1은 현재 위치, 2는 파일 맨 마지막이 기준 위치가 된다.


파일 이름변경과 삭제:

rename() 문법:

os.rename(current_file_name, new_file_name)


remove() 문법:

os.remove(file_name)


파이썬에서 디렉토리:

mkdir() 메소드:

mkdir() 메소드는 현재 디렉토리에서 디렉토리를 생성한다. 인자로 생성할 디렉토리명이 필요하다.

문법:

os.mkdir("newdir")


chdir() 메소드:

chdir() 메소드는 현재 디렉토리를 변경한다. chdir() 메소드는 변경하고자 하는 디렉토리명이 인자로 필요하다.

문법:

os.chdir("newdir")


getcwd() 메소드:

getcwd() 는 현재 작업 디렉토리를 보여준다.

문법:

os.getcwd()


rmdir() 메소드:

rmdir() 메소드는 인자로 넘겨준 디렉토리를 삭제한다.

디렉토리를 삭제하기 전에 디렉토리에 있는 모든 컨텐츠가 지워져 있어야 한다.

문법:

os.rmdir('dirname')


예외처리(Handling an exception):

예외가 발생될 수 있는 의심되는 코드(suspicious code)가 있다면, try: 블록으로 예외를 처리할 수 있다. except: 문을 포함한 try: 블록은 가능한 예외를 처리할 수 있다. 

문법:

간단한 try....except...else 블록 코드 예제:

try:
   Do you operations here;
   ......................
except ExceptionI:
   If there is ExceptionI, then execute this block.
except ExceptionII:
   If there is ExceptionII, then execute this block.
   ......................
else:
   If there is no exception then execute this block. 

위에서 보여준 문법에 중요한 내용이 있다:

  • 하나의 try 문은 여러 except 문을 가질 수 있다. 이는 다양한 예외를 내고 다르게 처리할 때 유용하게 사용된다.

  • 어떤 예외도 처리할 수 있도록 일반적인 except 구문(generic except clause)을 제공한다.

  • except문에서 else-구문을 포함할 수 있다. 이 코드는 try: 블록에서 예외 처리하지 되지 않은 코드를 else블록은 실행한다. 

  • else-블록은 try: 블록의 보호가 필요하지 않은 코드에 유용하게 활용된다.


The except clause with no exceptions:

아래와 같이 except 다음에 예외없이 except문을 사용할 수 있다.:

try:
   Do you operations here;
   ......................
except:
   If there is any exception, then execute this block.
   ......................
else:
   If there is no exception then execute this block. 


The except clause with multiple exceptions:

아래와 같이, 동일한 except문 안에서 여러 예외를 처리할 수있다:

try:
   Do you operations here;
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there is any exception from the given exception list, 
   then execute this block.
   ......................
else:
   If there is no exception then execute this block. 


Standard Exceptions:

파이썬에서 표준 예외 목록은 여기에 있다: Standard Exceptions


The try-finally clause:

try: 블록과 함께 finally: 블록을 함께 쓸수 있다. 이 finally 블록은 try-블록에서 예외가 발생하든지 안하든지 무조건 실행되는 블록이다. try-finally 문장은 아래와 같다:

try:
   Do you operations here;
   ......................
   Due to any exception, this may be skipped.
finally:
   This would always be executed.
   ......................


예외처리 인자(Argument of an Exception):

예외처리(exception)는 문제에 대한 추가적인 정보를 전달하기 위해 인자를 가질수 있다. 인자의 내용은 예외에 따라 다양하다. except 구문에서 인자를 받기위해 변수를 사용한다:

try:
   Do you operations here;
   ......................
except ExceptionType, Argument:
   You can print value of Argument here...


예외 발생(Raising an exceptions):

raise 문을 통해 몇몇 방법으로 예외를 발생시킬 수 있다. 일반적인 raise 문의 문법은 아래와 같다.

문법:

raise [Exception [, args [, traceback]]]


사용자 정의 예외(User-Defined Exceptions):

파이썬은 표준 빌트인 예외로 부터 파생된 자신만의 예외를 만들 수 있다.

여기에 RuntimeError 관련된 예제이다. 이 클래스는 RuntimeError로 부터 나온 서브클래스이다. 이 클래스는 예외를 처리할때 보다 자세한 정보를 보여줄때 유용하다. 

try 블록에서 사용자 정의 예외가 발생되고, except 블록에서 잡는다. 변수 e는 클래스 Networkerror 인스턴스를 생성할때 사용된다. 

class Networkerror(RuntimeError):
   def __init__(self, arg):
      self.args = arg

위의 클래스가 정의될 때, 아래와 같이 예외(exception)가 발생된다:

try:
   raise Networkerror("Bad hostname")
except Networkerror,e:
   print e.args


클래스 생성:

클래스 문자은 새로운 클래스 정의를 생성한다. 클래스명은 class라는 키워드 바로 다음에 오고 뒤에 콜론이 따른다:

class ClassName:
   'Optional class documentation string'
   class_suite
  • 클래스는 클래스명.__doc__ 으로 접근할 수 있는 도큐멘트 문자열을 갖는다.

  • class_suite 는 클래스 멤버, 데이타 속성과 함수를 포함한 모든 컴포넌트 문장으로 구성된다.


인스턴스 객체 생성:

클래스 인스턴스를 생성하기 위해 클래스명과 __init__ 메소드에 전달할 인자들이 필요하다.

"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)


접근 속성(Accessing attributes):

객체에 점(.) 연산자를 통해 객체 속성을 접근가능하다. 클래스 변수는 아래와 같이 클래스를 통해 접근한다:

emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount


빌트인 속성(Built-In Class Attributes):

모든 파이썬 클래스는 빌트인 속성을 가지고 있고, 점(.) 연산자로 다른 속성처럼 접근할 수 있다.:

  • __dict__ : 딕셔너리는 클래스의 네임스페이스를 포함한다.

  • __doc__ : 클래스 도큐멘트 문자열 또는 정의되어 있지않으면 없다.

  • __name__: 클래스명.

  • __module__: 클래스에 정의된 모듈명. 이 속성은 __main__ 대화모드이다.

  • __bases__ : 기본 클래스 목록에서 발생빈도를 가지고 있기 위해ㅔ 가능한 비어있는 튜플(tuple)이 기본 클래스를 가지고 있다.


객체 삭제(Garbage Collection):

파이썬은 필요하지 않는 객체(빌트인 클래스 또는 클래스 인스턴스)를 메모리를 해제시키기 위해 자동으로 지운다. 이 프로세스는 파이썬에 의해 주기적으로 더이상 필요하지 않는 메모리를 반납하는데 이를 가비지 콜렉션이라고 한다.

파이썬의 가비지 콜렉터는 프로그램이 실행되고, 객체 참조 횟수가 0이 될때 실행된다. 객체의 참조 횟수는 객체 변화 횟수를 가리킨다:

객체 참조 횟수는 컨테이너(list, tuple, 또는 dictionary)안에 새로운 이름 또는 새로운 위치될때 증가된다. 객체 참조 횟수는 del에 의해 지워지거나, 참조가 다시 대입되거나, 참조가 범위를 벗어날때 줄어든다. 객체 참조 횟수가 0가 되면 파이썬은 자동으로 메모리를 회수한다.


클래스 상속:

새로운 클래스명 뒤에 오는 괄호안에 기 존재하는 클래스를 정의함으로써 부모 클래스로부터 상속받을 수 있다:

자식 클래스는 부모 클래스의 속성을 상속받고, 자식 클래스에 정의되어 있는 다른 속성 처럼 상속받은 속성을 사용할 수 있다. 또한 자식 클래스는 부모클래스의 데이터멤버와 메소드를 오버라이드(override)할 수 있다.

문법:

파생된 클래스는 부모클래스와 같이 선언되지만, 클래스명 뒤에 상속받기 위해서는 부모 클래스를 나열한다. 아래는 예시이다:

class SubClassName (ParentClass1[, ParentClass2, ...]):
   'Optional class documentation string'
   class_suite


오버라이딩(Overriding) 메소드:

부모 클래스 메소드를 오버라이드할 수 있다. 부모 클래스를 오버라이딩하는 이유는 자식 클래스에서 특별하고 다른 기능을 원할수 도 있기 때문이다.

class Parent:        # define parent class
   def myMethod(self):
      print 'Calling parent method'

class Child(Parent): # define child class
   def myMethod(self):
      print 'Calling child method'

c = Child()          # instance of child
c.myMethod()         # child calls overridden method


기본적인 오버라이딩 메소드:

아래 표는 클래스에서 오버라이드 할 수 있는 몇가지 일반적인 함수를 보여준다:

SNMethod, Description & Sample Call
1__init__ ( self [,args...] )
Constructor (with any optional arguments)
Sample Call : obj = className(args)
2__del__( self )
Destructor, deletes an object
Sample Call : dell obj
3__repr__( self )
Evaluatable string representation
Sample Call : repr(obj)
4__str__( self )
Printable string representation
Sample Call : str(obj)
5__cmp__ ( self, x )
Object comparison
Sample Call : cmp(obj, x)


오버로딩 연산자(Overloading Operators):

2차 벡터를 표현하기 위해 벡터 클래스를 생성한다고 가정하자. 추가적인 연산자를 사용하고자 할때 어떻겠는가? 

연산자 추가를 위해 클래스에서 __add__ 메소드를 정의할 수 있다. 추가된 연산자는 원하는대로 수행할 것이다.:

#!/usr/bin/python

class Vector:
   def __init__(self, a, b):
      self.a = a
      self.b = b

   def __str__(self):
      return 'Vector (%d, %d)' % (self.a, self.b)
   
   def __add__(self,other):
      return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2


데이터 은닉(Data Hiding):

객체 속성은 클래스 정의 밖에서 보일수도 있고 보이지 않을 수도 있다. 이를 위해 두개 밑줄(__)와 함께 속성을 정의하면, 이러한 속성들은 밖에서 직접 볼 수 없다.:

#!/usr/bin/python

class JustCounter:
   __secretCount = 0
  
   def count(self):
      self.__secretCount += 1
      print self.__secretCount

counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount

정규식 표현(regular expression)  문자열 또는 문자열 집합을 매치(match)하고 찾기 위한 특별한 문자의 연속이다. 이는 패턴에서 정해진 문법을 사용한다. 정규식 표현(Regular expression)은 UNIX에서 광범위하게 활용된다.

re 모듈은 파이썬에서 펄(Perl)과 같은 정규식을 제공한다. re 모듈은 컴파일 또는 정규식 사용시에 예외가 발생하면 re.error라를 예외를 발생시킨다.

정규식을 처리하기 위해 사용되는 주요 두가지 기능이 있다. 첫번째는 정규식을 사용하는데 있어 특별한 의미를 갖는 다양한 문자가 있다. 또한 정규식을 다루는데 있어 혼동을 피하기 위해 r'표현을 통해 원천 문자열(Raw Strings)을 사용할 수 있다.


match 함수

이 함수는 선택적 플래그와 함께 문자열의 RE 패턴을 매치시킨다.

아래 이 함수에 대한 문법 예시가 있다:

re.match(pattern, string, flags=0)

아래는 파라미터에 대한 설명이 있다:

ParameterDescription
pattern매치해야할 정규식 표현(regular expression) 이다.
string

패턴을 찾을 문자열이다.

flags

배타적인 OR를 사용하여 다른 플래그를 설정할 수 있다. 아래 표 변경자 목록이 있다.

re.match 함수는 성공시에 match 객체를 돌려주고, 실패시에는 아무것도 돌려주지 않는다(None). 또한 매치된 표현을 가져오기 위해서는 match 객체의 usergroup(num) 또는 groups() 함수를 사용한다.

Match Object MethodsDescription
group(num=0)

이 메소드는 전체 매치된 객체를 돌려준다(또는 특별히 서브그룹 num)

groups()

이 메소드는 튜플(tuple)에 모든 매칭된 서브 그룹을 돌려준다(매치된 객체가 없으면 empty)


search 함수:

이 함수는 선택적 플래그와 RE 패턴 문자열의 첫번째 위치를 돌려준다.

아래는 이 함수에 대한 예시이다:

re.string(pattern, string, flags=0)

아래는 파라미터에 대한 설명이다:

ParameterDescription
pattern 매치해야할 정규식 표현(regular expression) 이다.
string 패턴을 찾을 문자열이다.
flags배타적인 OR를 사용하여 다른 플래그를 설정할 수 있다. 아래 표 변경자 목록이 있다.

re.search 함수는 성공시에 match 객체를 돌려주고, 실패시에는 아무것도 돌려주지 않는다(None). 또한 매치된 표현을 가져오기 위해서는 match 객체의 usergroup(num) 또는 groups() 함수를 사용한다.

Match Object MethodsDescription
group(num=0)

이 메소드는 전체 매치된 객체를 돌려준다(또는 특별히 서브그룹 num)

groups()이 메소드는 튜플(tuple)에 모든 매칭된 서브 그룹을 돌려준다(매치된 객체가 없으면 empty)


일치 vs 찾기(Matching vs Searching):

파이썬은 정규표현식 기반에 기본적으로 2가지 함수를 제공한다: match는 문자열의 첫번째에서 일치되는지를 반면에 search는 문자열 어느 곳이든 일치되는 지를 체크한다.


찾기와 대체(Search and Replace):

정규 표현식을 사용하는 가장 중요한 re 메소드 일부는 sub이다.

문법:

sub(pattern, repl, string, max=0)

이 메소드는 문자열에서 RE 패턴에 해당되는 부분을 max가 지정되지 않으면, 모두 repl로 대체한다. 이 메소드는 수정된 문자열을 리턴한다.

Regular-expression Modifiers - Option Flags

Regular expression literals may include an optional modifier to control various aspects of matching. The modifier are specified as an optional flag. You can provide multiple modified using exclusive OR (|), as shown previously and may be represented by one of these:

ModifierDescription
re.IPerforms case-insensitive matching.
re.LInterprets words according to the current locale.This interpretation affects the alphabetic group (\w and \W), as well as word boundary behavior (\b and \B).
re.MMakes $ match the end of a line (not just the end of the string) and makes ^ match the start of any line (not just the start of the string).
re.SMakes a period (dot) match any character, including a newline.
re.UInterprets letters according to the Unicode character set. This flag affects the behavior of \w, \W, \b, \B.
re.XPermits "cuter" regular expression syntax. It ignores whitespace (except inside a set [] or when escaped by a backslash), and treats unescaped # as a comment marker.

Regular-expression patterns:

Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \), all characters match themselves. You can escape a control character by preceding it with a backslash.

Following table lists the regular expression syntax that is available in Python.

PatternDescription
^Matches beginning of line.
$Matches end of line.
.Matches any single character except newline. Using m option allows it to match newline as well.
[...]Matches any single character in brackets.
[^...]Matches any single character not in brackets
re*Matches 0 or more occurrences of preceding expression.
re+Matches 0 or 1 occurrence of preceding expression.
re{ n}Matches exactly n number of occurrences of preceding expression.
re{ n,}Matches n or more occurrences of preceding expression.
re{ n, m}Matches at least n and at most m occurrences of preceding expression.
a| bMatches either a or b.
(re)Groups regular expressions and remembers matched text.
(?imx)Temporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected.
(?-imx)Temporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected.
(?: re)Groups regular expressions without remembering matched text.
(?imx: re)Temporarily toggles on i, m, or x options within parentheses.
(?-imx: re)Temporarily toggles off i, m, or x options within parentheses.
(?#...)Comment.
(?= re)Specifies position using a pattern. Doesn't have a range.
(?! re)Specifies position using pattern negation. Doesn't have a range.
(?> re)Matches independent pattern without backtracking.
\wMatches word characters.
\WMatches nonword characters.
\sMatches whitespace. Equivalent to [\t\n\r\f].
\SMatches nonwhitespace.
\dMatches digits. Equivalent to [0-9].
\DMatches nondigits.
\AMatches beginning of string.
\ZMatches end of string. If a newline exists, it matches just before newline.
\zMatches end of string.
\GMatches point where last match finished.
\bMatches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets.
\BMatches nonword boundaries.
\n, \t, etc.Matches newlines, carriage returns, tabs, etc.
\1...\9Matches nth grouped subexpression.
\10Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code.

Regular-expression Examples:

Literal characters:

ExampleDescription
pythonMatch "python".

Character classes:

ExampleDescription
[Pp]ythonMatch "Python" or "python"
rub[ye]Match "ruby" or "rube"
[aeiou]Match any one lowercase vowel
[0-9]Match any digit; same as [0123456789]
[a-z]Match any lowercase ASCII letter
[A-Z]Match any uppercase ASCII letter
[a-zA-Z0-9]Match any of the above
[^aeiou]Match anything other than a lowercase vowel
[^0-9]Match anything other than a digit

Special Character Classes:

ExampleDescription
.Match any character except newline
\dMatch a digit: [0-9]
\DMatch a nondigit: [^0-9]
\sMatch a whitespace character: [ \t\r\n\f]
\SMatch nonwhitespace: [^ \t\r\n\f]
\wMatch a single word character: [A-Za-z0-9_]
\WMatch a nonword character: [^A-Za-z0-9_]

Repetition Cases:

ExampleDescription
ruby?Match "rub" or "ruby": the y is optional
ruby*Match "rub" plus 0 or more ys
ruby+Match "rub" plus 1 or more ys
\d{3}Match exactly 3 digits
\d{3,}Match 3 or more digits
\d{3,5}Match 3, 4, or 5 digits

Nongreedy repetition:

This matches the smallest number of repetitions:

ExampleDescription
<.*>Greedy repetition: matches "<python>perl>"
<.*?>Nongreedy: matches "<python>" in "<python>perl>"

Grouping with parentheses:

ExampleDescription
\D\d+No group: + repeats \d
(\D\d)+Grouped: + repeats \D\d pair
([Pp]ython(, )?)+Match "Python", "Python, python, python", etc.

Backreferences:

This matches a previously matched group again:

ExampleDescription
([Pp])ython&\1ailsMatch python&pails or Python&Pails
(['"])[^\1]*\1Single or double-quoted string. \1 matches whatever the 1st group matched . \2 matches whatever the 2nd group matched, etc.

Alternatives:

ExampleDescription
python|perlMatch "python" or "perl"
rub(y|le))Match "ruby" or "ruble"
Python(!+|\?)"Python" followed by one or more ! or one ?

Anchors:

This need to specify match position

ExampleDescription
^PythonMatch "Python" at the start of a string or internal line
Python$Match "Python" at the end of a string or line
\APythonMatch "Python" at the start of a string
Python\ZMatch "Python" at the end of a string
\bPython\bMatch "Python" at a word boundary
\brub\B\B is nonword boundary: match "rub" in "rube" and "ruby" but not alone
Python(?=!)Match "Python", if followed by an exclamation point
Python(?!!)Match "Python", if not followed by an exclamation point

Special syntax with parentheses:

ExampleDescription
R(?#comment)Matches "R". All the rest is a comment
R(?i)ubyCase-insensitive while matching "uby"
R(?i:uby)Same as above
rub(?:y|le))Group only without creating \1 backreference


[출처] http://www.tutorialspoint.com/python/python_quick_guide.htm