python Package

Package

  • Structure gathering many modules in one directory physically
    • Top directory’s name is the package’s name
    • Sub directories under the Top directory become sub-package of the top package
    • Module = file, package = directory

Role of __init__.py

  • The role recognizing the directory as a package
  • For sub-packes, this file is requried(if not, that will be usual folder)

Doing import

1
import Speech
  • Speechdirectory should be one of the directories of sys.path(or PYTHONPATH environment variable)
  • Let’s say Speech/Recognition/HMM.py looks like this
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    def train():
    print "Train"
    pass

    def loadModel():
    print "LoadModel"
    pass

    def saveModel():
    print "SaveModel"
    pass

How to use specific function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# can't use. from package's name, we need dot(.) for calling the module or function
import Speech
Speech.Recognition.HMM.train()

# Proper way
import Speech.Recognition.HMM
Speech.Recognition.HMM.train()

from Speech.Recognition import HMM
HMM.train()

from Speech.Recognition.HMM import train
train()

# Taking everything from the module. It can be used without the module's name
from Speech.Recognition.HMM import *
train()
loadModel()
saveModel()
Comments

python 모듈 import하기

import 모듈명

  1. 기본적인 형태

    1
    2
    import mymath
    print mymath.area(5)
  2. from 모듈명 import 가져올 대상

    • 해당 모듈에 존재하는 대상을 가져옴
    • 기존에 존재하던 이름이면 기존 객체가 상실됨
    • 모듈 이름 없이 바로 사용 가능
      1
      2
      from mymath import area, mypi
      print area(5)
  3. from 모듈명 import *

    • 해당 모듈에 존재하는 __로 시작되는 것들을 제외한 모든 대상을 가져옴
      1
      2
      from mymath import *
      print area(5)
  4. import 모듈명 as 새로운 모듈 이름

    • 해당 모듈을 다른 이름으로 사용하고자 할 때 사용
    • 기존 모듈 이름이 너무 길거나 현재 사용중인 이름인 경우 유용
      1
      2
      3
      4
      import string as chstr
      print chstr
      print
      print chstr.punctuation
  5. from 모듈명 import 이름 as 새로운 이름[, 이름 as 새로운 이름]

    • 해당 모듈 내에 정의된 이름을 새로운 이름으로 사용하고자 할 때
      1
      2
      3
      4
      5
      6
      from string import replace as substitute[, upper as up]
      print substitute
      print substitute('ham chicken spam', 'chicke', 'egg')

      print up
      print up('abc')
  • import문은 어디에서나 사용가능(함수 내에서도 가능)

컴파일과 적재시간

  • import mymath를 수행할 때 발생하는 일

    1. mymath.pyc를 찾는다
    2. 없다면 mymath.py를 찾아서 mymath.pyc를 생성한다
    3. mymath.pyc를 메모리로 읽어들여 수행한다
  • .pyc파일

    1. 바이트 코드 파일

      • 기계나 플랫폼(운영체제 등)에 의존하지 않도록 만들어진 일종의 목적 코드(Object code)
      • 파이썬은 컴파일 언어이면서 동시에 인터프리터 언어의 수행 방식을 취함
    2. 새로운 .pyc파일 생성에 대한 판단

      • .py수정시간이 .pyc수정 시간보다 더 최근일 때
    3. .py가 없이 .pyc파일만 있어도 import가능
      • 코드를 숨기는 방법으로 활용 가능

같은 이름을 다시 사용할 때

  • 같은 이름 사용하면 이전의 내용이 삭제되지만 모듈은 메모리에 남아있고, 다시 import하면 다시 가져오는 것이 아니라 메모리에 존재하는 모듈을 활용함. 따라서 기존에 추가 정의한 내용들 사용가능

모듈의 실행과 테스트 코드

  • __name__

    • 현재의 모듈이 최상위 모듈로서 수행되는지, 아니면다른 모듈에 의해 imort되어 수행되는지를 구별하기 위해 주로 사용
    • 최상위 모듈에서 사용할 때 -> __main__
    • 다른 모듈에서 사용될 때 -> 해당 모듈의 이름

      1
      2
      3
      4
      print __name__ # __main__ 출력

      import prname
      print prname.__name__ # prname출력
    • 사용방법

      1
      2
      3
      4
      5
      6
      7
      8
      9
      def add(a, b):
      return a + b

      def f():
      print "Python is becoming popular."

      if __name__ == "__main__":
      print add(1, 10)
      f()
      • 직접 실행할 때는 if절 동작
      • 다른 곳에서 활용할 경우 if절 무시
Comments

python module importing

import module’s name

  1. Basic form

    1
    2
    import mymath
    print mymath.area(5)
  2. from module’s name import wanted object

    • taking the wanted object from the module
    • original object is lost if the name is using
    • it can be used without the module’s name
      1
      2
      from mymath import area, mypi
      print area(5)
  3. from module’s name import *

    • taking everything from the module without objects starting __
      1
      2
      from mymath import *
      print area(5)
  4. import module’s name as another module name

    • another name is used for calling the module
    • It is recommended when the original name is too long or already used
      1
      2
      3
      4
      import string as chstr
      print chstr
      print
      print chstr.punctuation
  5. from module’s name import original name as another name[, name2 as another name2]

    • another name is used for calling the module
      1
      2
      3
      4
      5
      6
      from string import replace as substitute[, upper as up]
      print substitute
      print substitute('ham chicken spam', 'chicke', 'egg')

      print up
      print up('abc')
  • import can be used anywhere(including in a function)

Compile and Load time

  • import mymath works like this

    1. Finding mymath.pyc
    2. If that doesn’t exist, Finding mymath.py and creating mymath.pyc
    3. Loading mymath.pyc into memory and executing
  • .pyc file

    1. Byte code file

      • Kind of Object code not depending on machines or platform(OS)
      • Python takes both executing ways of compile language and interpreter language
    2. Deciding about creating new .pycfile

      • When modificatin time of .py is more recently than modification time of .pyc
    3. Without .pyfile, import is available with .pyc
      • It can be use as the way to hide the original code

Using the same name again

  • Though the name’s target is changed, the module remains in memory, if we import the module, that takes the module existing in memory. So, we can use the thing we defined additionally in the module at the code

Executing module and test code

  • __name__

    • It is usually used for knowing if this module is used as the root module or in other module by import
    • Being used as the root module -> __main__
    • Being used in other module -> that module’s name

      1
      2
      3
      4
      print __name__ # __main__ print

      import prname
      print prname.__name__ # prname print
    • How to use

      1
      2
      3
      4
      5
      6
      7
      8
      9
      def add(a, b):
      return a + b

      def f():
      print "Python is becoming popular."

      if __name__ == "__main__":
      print add(1, 10)
      f()
      • Direct executing runs if statement
      • Being used in other module ignores if statement
Comments

python lambda function

the definition of lambda function

  • new literal defining usual functions by one line
  • usually it is used for defining one-time functions
  • after :, only expression can follow
  • lambda function is An object too
1
2
f = lambda x: x + 1
print f(1)
  1. Assigning variables and calling the lambda function having two parameters

    1
    2
    g = lambda x,y: x + y
    print g(1,2)
  2. Defining the lambda function having default argument

    1
    2
    3
    g = lambda x, inc=1: x+inc
    print g(10) # default argument(inc=1) value is used
    print g(10, 5)
  3. Defining the lambda function having variable argument

    1
    2
    3
    #args is returned
    vargs = lambda x, *args: args
    print vars(1,2,3,4,5)

Using lambda functions

  • Using usual function

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    def f1(x):
    return x*x + 3*x - 10

    def f2(x):
    return x*x*x

    def g(func):
    return [func(x) for x in range(-10, 10)]

    print g(f1)
    print g(f2)
  • Usiung lambda function

    1
    2
    3
    4
    5
    def g(func):
    return [func(x) for x in range(-10, 10)]

    print g(lambda x: x*x + 3*x - 10)
    print g(lambda x: x*x*x)

Utilizing lambda function

  • map, filter, reduce built-in functions
  1. map built-in function

    • map(function, seq): taking item by item in seq and running function with the item and returning the result as the type of seq

      1
      2
      3
      4
      5
      def f(x):
      return x * x
      X - [1,2,3,4,5]
      Y = map(f, X)
      print Y
    • Using map and lambda function - most recommended

      1
      2
      X = [1,2,3,4,5]
      print map(lambda x: x * x, X)
  2. filter built-in function

    • taking item by item in seq and running function with the item and returning the result as the type of seq if the result is True
      1
      print filter(lambda x: x>2, [1,2,3,45])
  3. reduce built-in function

    • reduce(function, seq[,initial])
    • about each items in seq, applying function and mapping as A value
    • the 1st paremeter(function) should take two values(ex: x,y)
      1. the items of seq get into y
      2. the result after calling the function gets into x
    • optionally, the 3rd parameter initial is used as default value of x at the 1st step
      1
      2
      print reduce(lambda x, y: x + y, [1,2,3,4,5])
      print reduce(lambda x, y: x + y, [1,2,3,4,5], 1000)
Comments

python 람다(lambda) 함수

람다(lambda)함수 정의

  • 일반적인 함수를 한 줄의 문으로 정의할 수 있는 새로운 함수 정의 리터럴
  • 일회성으로 활용할 함수 정의할 때 주로 사용
  • :뒤에는 식만 올 수 있음
  • 람다 함수도 하나의 객체임
1
2
f = lambda x: x + 1
print f(1)
  1. 인수가 두 개 있는 람다 함수를 지니는 변수 지정 및 함수 호출

    1
    2
    g = lambda x,y: x + y
    print g(1,2)
  2. 기본 인수를 지니는 람다 함수 정의

    1
    2
    3
    g = lambda x, inc=1: x+inc
    print g(10) # inc기본 인수 값으로 1사용
    print g(10, 5)
  3. 가변 인수를 지니는 람다 함수 정의

    1
    2
    vargs = lambda x, *args: args #args가 리턴됨
    print vars(1,2,3,4,5)

람다 함수 사용하기

  • 일반 함수 사용

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    def f1(x):
    return x*x + 3*x - 10

    def f2(x):
    return x*x*x

    def g(func):
    return [func(x) for x in range(-10, 10)]

    print g(f1)
    print g(f2)
  • 람다 함수 사용

    1
    2
    3
    4
    5
    def g(func):
    return [func(x) for x in range(-10, 10)]

    print g(lambda x: x*x + 3*x - 10)
    print g(lambda x: x*x*x)

람다 함수 활용

  • map, filter, reduce 내장 함수
  1. map 내장 함수

    • map(function, seq): seq의 원소를 차례로 돌면서 function에 적용한 결과를 seq의 자료형으로 반환

      1
      2
      3
      4
      5
      def f(x):
      return x * x
      X - [1,2,3,4,5]
      Y = map(f, X)
      print Y
    • map과 람다 함수를 동시에 사용 - 가장 추천

      1
      2
      X = [1,2,3,4,5]
      print map(lambda x: x * x, X)
  2. filter 내장 함수

    • seq자료형이 지닌 각 원소값에 대해 function에 적용한 결과가 참인 원소값들만을 동일 시퀀스 자료형으로 반환
      1
      print filter(lambda x: x>2, [1,2,3,45])
  3. reduce 내장 함수

    • reduce(function, seq[,initial])
    • seq자료형이 지닌 각 원소값에 대해 function함수를 적용하면서 하나의 값으로 매핑
    • 첫번째 인자(function)는 반드시 두 개의 인자(ex. x,y)를 받아야한다.
      • seq의 각 원소값들이 차례로 y에 들어간다
      • 함수가 수행된 값은 차례대로 x에 들어간다
    • 추가적으로 제공가능한 세번재 인자인 initial은 첫번째 단계에서 x에 할당할 초기값으로 사용된다
      1
      2
      print reduce(lambda x, y: x + y, [1,2,3,4,5])
      print reduce(lambda x, y: x + y, [1,2,3,4,5], 1000)
Comments

python operating files

Operating files

Opening file list

Using osmodule

1
2
3
4
5
6
import os

print os.listdir('.') # file list of present directory
print

print os.listdir('../') # file list of parent directory


Recognizing file’s category

  • os.pathmodule recognizes and returns True or False
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import os
    def filetype(fpath):
    print fpath, ":",
    if os.path.isfile(fpath):
    print 'Regular file'
    if os.path.isdir(fpath):
    print 'Directory'
    if os.path.islink(fpath):
    print 'Symbolic link'

    flist = os.listdir('.')
    for fname in flist:
    filetype(fname)

Permission about file

  1. Learning permission about file

    • os.access(filepath, mode)
      • the values we can put for mode
        • os.F_OK: testing if the file exists
        • os.R_OK: testing about reading permission
        • os.W_OK: testing about writing permission
        • os.X_OK: testing about opening or executing permission
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import os
    def fileaccess(fpath):
    print fpath, ':',
    if os.access(fpath, os.F_OK):
    print 'Exists',
    else:
    return
    if os.access(fpath, os.R_OK):
    print 'R',
    if os.access(fpath, os.W_OK):
    print 'W',
    if os.access(fpath, os.X_OK):
    print 'X',
    print

    flist = os.listdir('.')
    for fname in flist:
    fileaccess(fname)
  2. Chagning the Permission for the file

    • os.chmod(filepath, mode)
    1
    2
    import os
    os.chmod('sample.txt', 0777)

Manipulating files

  1. Chagning the name of the file

    • os.rename(old_filepath, new_filepath)
    1
    2
    3
    4
    5
    import os
    os.rename('t.txt', 't1.txt')

    print os.access('t.txt', os.F_OK) # checking if the file exists
    print os.access('t1.txt', os.F_OK)
  2. Moving the file

    • os.rename(oldfilepath, new_filepath)

      1
      2
      3
      4
      5
      import os
      os.rename('t.txt', 'example/t1.txt')

      # checking if the file exists
      print os.access('example/t1.txt', os.F_OK)
  3. Copying the file

    • shutilmodule is used
    • shutil.copyfile(src_filepath, dest_filepath)
    1
    2
    3
    4
    import os
    import shutil
    shutil.copyfile('sample.txt', 'sample_new.txt')
    print os.access('sample_new.txt', os.F_OK)

Manipulating the path of the file

  1. Changing relative path to absolute path

    • os.path.abspath - relative path
      • no matter the existance of the file, it changes the path to absolute path
        1
        2
        import os
        print os.path.abspath('o.txt')
  2. Checking if the file exists in the given path

    • os.path.exists(filepath)

Dividing path name

  1. Dividing path and file’s name

    1
    2
    3
    4
    f = '/Users/booski/git/python/t.txt'

    print os.path.basename(f) # extracting only the file's name
    print os.path.dirname(f) # extracting the directory's name
  2. Dividing path and file’s name by one line - basename and dirname are made in a tuple

    1
    print os.path.split(f)
  3. Dividing drive’s name and file path in MS windows

    1
    print os.path.splitdrive(f)
  4. Dividing extension - path and extension are made in a tuple

    1
    print os.path.splitext(f)
Comments

python 파일 다루기

파일 다루기

파일 목록열기

os모듈 사용

1
2
3
4
5
6
import os

print os.listdir('.') #현재 디렉토리의 파일목록
print

print os.listdir('../') #현재 디렉토리의 부모 디렉토리의 파일 목록


파일 종류 알아보기

  • os.path 모듈로 파일 종류 판단하여 True, False 반환
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import os
    def filetype(fpath):
    print fpath, ":",
    if os.path.isfile(fpath):
    print 'Regular file'
    if os.path.isdir(fpath):
    print 'Directory'
    if os.path.islink(fpath):
    print 'Symbolic link'

    flist = os.listdir('.')
    for fname in flist:
    filetype(fname)

파일의 허가권

  1. 파일의 허가권 알아보기

    • os.access(filepath, mode)
      • mode에 들어갈 값
        • os.F_OK: 파일 자체가 존재하는 것을 테스트
        • os.R_OK: 읽기 권한이 있는 것을 테스트
        • os.W_OK: 쓰기 권한이 있는 것을 테스트
        • os.X_OK: 실행 권한이 있는 것(또는 디렉토리인지)을 테스트
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import os
    def fileaccess(fpath):
    print fpath, ':',
    if os.access(fpath, os.F_OK):
    print 'Exists',
    else:
    return
    if os.access(fpath, os.R_OK):
    print 'R',
    if os.access(fpath, os.W_OK):
    print 'W',
    if os.access(fpath, os.X_OK):
    print 'X',
    print

    flist = os.listdir('.')
    for fname in flist:
    fileaccess(fname)
  2. 파일의 허가권 변경하기

    • os.chmod(filepath, mode)
    1
    2
    import os
    os.chmod('sample.txt', 0777)

파일 조작하기

  1. 파일 이름 변경하기

    • os.rename(old_filepath, new_filepath)
    1
    2
    3
    4
    5
    import os
    os.rename('t.txt', 't1.txt')

    print os.access('t.txt', os.F_OK) # 파일 존재 여부 확인
    print os.access('t1.txt', os.F_OK)
  2. 파일 이동하기

    • os.rename(oldfilepath, new_filepath)

      1
      2
      3
      4
      5
      import os
      os.rename('t.txt', 'example/t1.txt')

      # 파일 존재 여부 확인
      print os.access('example/t1.txt', os.F_OK)
  3. 파일 복사하기

    • shutil모듈 활용
    • shutil.copyfile(src_filepath, dest_filepath)
    1
    2
    3
    4
    import os
    import shutil
    shutil.copyfile('sample.txt', 'sample_new.txt')
    print os.access('sample_new.txt', os.F_OK)

파일 이름 다루기

  1. 상대 경로를 절대 경로로 변환하기

    • os.path.abspath - 상대경로
      • 실제 파일 존재와는 무관하게 절대경로로 변경
        1
        2
        import os
        print os.path.abspath('o.txt')
  2. 주어진 경로에 파일이 존재하는지 확인

    • os.path.exists(filepath)

경로명 분리하기

  1. 경로와 파일명으로 분리

    1
    2
    3
    4
    f = '/Users/booski/git/python/t.txt'

    print os.path.basename(f) # 파일명만 추출
    print os.path.dirname(f) # 디렉토리 경로 추출
  2. 경로명과 파일명을 한번에 분리 - basename과 dirname을 튜플로 확인

    1
    print os.path.split(f)
  3. MS윈도우즈에서 드라이브명과 파일 경로명을 분리

    1
    print os.path.splitdrive(f)
  4. 확장자 분리 - 경로와 확장자명으로 튜플 생성

    1
    print os.path.splitext(f)
Comments

python File Input&Output

File IO

  • mode can be set as the Second parameter of openbuilt-in function
    default value is read only(r)
  1. r - read only - file object is created in read only, file pointer moves to the beginning of the file, Error occurs if the file doesn’t exists
  2. w - write only - creating new file or creating new file object in write only after removing original file’s content, file pointer moves to the beginning of the file
  3. a - addding content at the bottom - creating file object in write only or creating new file if the file doesn’t exist and then putting the file pointer to the end of the file

Binary file mode

  • rb
  • wb
  • ab

It is recommended to close the file object by close() immediately like f.close()

Using read() assigns whole content after reading everything

Reading file line by line

  1. Using forloof statement

    1
    2
    3
    4
    5
    6
    f = open('t.txt')
    i = 1
    for line in f:
    print i, ":", line,
    i += 1
    f.close()
  2. readline() - from present file pointer to new line character = A line

    1
    2
    3
    4
    5
    6
    7
    8
    f = open('t.txt')
    line = f.readline()
    i = 1
    while line:
    print i, ":", line,
    line = f.readline()
    i += 1
    f.close()
  3. readlines() - Saving line by line in a list, memory is used inefficiently
    It works differently depending on each cases - for instatement: not reading everything, taking line by line

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    f = open('t.txt')
    print f.readlines() # returning a list

    # file pointer moves to the beginning of the file
    f.seek(0)

    i = 1
    for line in f.readlines():
    print i, ":", line,
    i += 1
    f.close()
  4. xreadlines() - memory inefficiency improved

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    f = open('t.txt')
    print f.xreadlines() # returning file object

    # file pointer moves to the beginning of the file
    f.seek(0)

    i = 1
    for line in f.xreadlines():
    print i, ":", line,
    i += 1
    f.close()

for in or xreadlines() are recommended


the way to write down line by line

  1. writelines() - for writing line by line

    1
    2
    3
    4
    5
    6
    7
    8
    lines = ['1st line\n', '2nd line\n', '3rd line\n']
    f = open('t1.txt','w')
    f.writelines(lines)
    f.close()

    f = open('t1.txt')
    print f.read() # reading whole content
    f.close()
  2. write() - putting \n between items

    1
    2
    3
    4
    5
    6
    7
    8
    lines = ['1st line', '2nd line', '3rd line']
    f = open('t1.txt','w')
    f.write('\n'.join(lines))
    f.close()

    f = open('t1.txt')
    print f.read() # reading whole content
    f.close()

Adding content in the existing file existing

  • Using mode a
    1
    2
    3
    4
    5
    6
    7
    f = open('removeme.txt', 'a')
    f.write('3rd line\n')
    f.close()

    f = open('removeme.txt')
    print f.read()
    f.close()

Seeking specific file pointer

  • Sequential access
  • specific access
    • seek(n) - moving file pointer to the point which is n byte far from the beginning of the file
    • tell() - returning present file pointer in the file
1
2
3
4
5
6
7
8
9
name = 't.txt'
f = open(name, 'w+') # read and write mode
s = '0123456789asdf'
f.write(s)

f.seek(5)
print f.tell()
print f.read(1)
print f.tell()

sys module’s standard IO(monitor) object

  • sys.stdout: standard Input and Output
  • sys.stderr: standard error Output
  • sys.stdin: standard Input

Saving a file by standard output

1
2
3
4
5
6
7
8
9
10
import sys

f = open('t.txt','w')
stdout = sys.stdout # saving standard output
sys.stdout = f # changing standard output to file object
print 'Sample output'
pirnt 'Good'
print 'Good'
f.close()
sys.stdout = stdout # restoring standard output
Comments

python 파일 입출력

파일 입출력

open내장 함수 사용시 두번째 인자값으로 mode설정
생략시 읽기전용(r)으로 설정

  1. r -읽기 전용 - 파일 객체를 읽기 모드로 생성, 파일 포인터를 파일 처음 위치로, 존재하지 않는 파일이면 에러발생
  2. w - 쓰기 전용 - 새로운 파일을 생성하거나 기존 파일의 내용을 다 없애고 쓰기모드로 생성, 파일 포인터를 파일 처음 위치로
  3. a - 파일 끝에 추가 - 이미 존재하는 파일을 쓰기모드로 생성하거나 존재하지 않으면 파일 만들고 생성, 파일 포인터를 마지막 위치에 놓음

이진파일 모드

  • rb
  • wb
  • ab

f.close()처럼 close()로 그때그때 닫아주는 것이 좋음

read()를 사용하면 전체를 다 읽어서 할당함

라인단위로 파일 읽기

  1. for 반복문 활용

    1
    2
    3
    4
    5
    6
    f = open('t.txt')
    i = 1
    for line in f:
    print i, ":", line,
    i += 1
    f.close()
  2. readline()-현재의 파일 포인터에서 개행 문자까지 읽음 = 한 라인

    1
    2
    3
    4
    5
    6
    7
    8
    f = open('t.txt')
    line = f.readline()
    i = 1
    while line:
    print i, ":", line,
    line = f.readline()
    i += 1
    f.close()
  3. readlines()-각 라인을 모두 읽어서 리스트로 저장, 메모리는 비효율적으로 사용
    상황별로 다른 동작함 - for in구문: 전체x, 라인별로 가져옴

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    f = open('t.txt')
    print f.readlines() #리스트 나옴

    #파일 포인터를 맨 앞으로
    f.seek(0)

    i = 1
    for line in f.readlines():
    print i, ":", line,
    i += 1
    f.close()
  4. xreadlines() - 메모리 비효율 개선

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    f = open('t.txt')
    print f.xreadlines() #파일객체 자체가 나옴

    #파일 포인터를 맨 앞으로
    f.seek(0)

    i = 1
    for line in f.xreadlines():
    print i, ":", line,
    i += 1
    f.close()

for in 또는 xreadlines() 추천


라인 단위로 쓰는 방법

  1. writelines() - 라인단위로 쓰기 작업

    1
    2
    3
    4
    5
    6
    7
    8
    lines = ['1st line\n', '2nd line\n', '3rd line\n']
    f = open('t1.txt','w')
    f.writelines(lines)
    f.close()

    f = open('t1.txt')
    print f.read() #전체내용 읽음
    f.close()
  2. write() - 임의로 중간에 ‘\n’ 넣어줌

    1
    2
    3
    4
    5
    6
    7
    8
    lines = ['1st line', '2nd line', '3rd line']
    f = open('t1.txt','w')
    f.write('\n'.join(lines))
    f.close()

    f = open('t1.txt')
    print f.read() #전체내용 읽음
    f.close()

기존 파일에 내용 추가

  • a모드 사용
    1
    2
    3
    4
    5
    6
    7
    f = open('removeme.txt', 'a')
    f.write('3rd line\n')
    f.close()

    f = open('removeme.txt')
    print f.read()
    f.close()

파일 내 임의 위치로 접근

  • 순차접근
  • 임의접근
    • seek(n) - 파일의 가장 첫번째 위치에서 n번째 바이트로 포인터이동
    • tell() - 파일 내 현재 포인터 위치를 반환
1
2
3
4
5
6
7
8
9
name = 't.txt'
f = open(name, 'w+') # 읽고 쓰기모드
s = '0123456789asdf'
f.write(s)

f.seek(5)
print f.tell()
print f.read(1)
print f.tell()

sys 모듈의 표준 입출력(모니터) 관련 객체

  • sys.stdout: 표준 입출력
  • sys.stderr: 표준 에러 출력
  • sys.stdin: 표준 입력

표준 출력으로 파일 저장하기

1
2
3
4
5
6
7
8
9
10
import sys

f = open('t.txt','w')
stdout = sys.stdout #표준 출력 저장
sys.stdout = f #파일 객체로 표준 출력 변경
print 'Sample output'
pirnt 'Good'
print 'Good'
f.close()
sys.stdout = stdout #표준 출력 복원
Comments

.gitignore, config파일 사용

새노트북

여러 프로젝트를 두 노트북에서 함께 진행할 예정인데 새 노트북에 기존 코드들을 넘겨와야함

데이터베이스 비밀번호 등 개인정보가 마음에 걸려서 설정파일로 빼보려고하니 일이 커짐

.gitignore사용한 것과 config폴더, 파일 사용법 포스팅할 예정

Comments