본문 바로가기
「 Basic 」/Python

6. 파일입출력

by BegginerBytes 2009. 2. 9.

파일을 임시나 영구적으로 파일로 저장을 할 수 있다.

표준 입출력인 sys모듈은 기본적으로 import하지 않아도 사용가능하지만 사용자가 직접 사용하기 때문에 직접 import 해준다.

sys.stdin, sys.stdout : 표준 입출력 스트림
sys.stderr : 표준 에러 스트림


파일 저장하기

c언어의  fopen() 함수와 동일하다.

import sys

try:
    ACFile = open("d:\\test.dat","w")
except IOError, message:
    print >> sys.stderr,"File could not be opend : ",message
    sys.exit(1)
while 1:
    try:
        Data = raw_input("insert any (If you wanna exit, typing 'quit') >>")
    except IOError:
        break
    else:
        if Data == "quit":
            break
        print>> ACFile, Data
ACFile.close()


저장 내용 불러오기

import sys

try:
    ACFile = open("d:\\test.dat","r")
except IOError, message:
    print >> sys.stderr,"File could not be opend : ",message
    sys.exit(1)

for x in ACFile:
    print x
    
ACFile.close()


불러올때 가독성을 높이기 위해서는 readlines() 함수를 써준다.

import sys

try:
    ACFile = open("d:\\test.dat","r")
except IOError, message:
    print >> sys.stderr,"File could not be opend : ",message
    sys.exit(1)

records = ACFile.readlines() #가독성 있게 한다.
for x in records:
    print x
    
ACFile.close()

공백을 기준으로 나누어서 출력을 할 경우 split() 함수를 사용하면 된다.


임의접근

순차적으로 접근하면, 원하는 레코드를 찾는데 많은 시간이 소요되는데, key값만 가지고 접근할 수 있게 해서 효율적인 접근을 한다. 사전 자료형과 비슷하게 사용하면 된다.

import sys
import shelve

try:
    outMon = shelve.open("d:\\mon.dat")
except:
    print "File Could not opened!"
    sys.exit(1)

print "Insert monster info!"
print "ID(1~100), NAME, POwer"
print "example : 10 Goblin 5"
print "If you wanna exit, write '0'"

while 1:
    tmp = raw_input(">")

    if tmp == "0":
        break
    tmp = tmp.split(" ",1) # 첫번째꺼 구문 구분
    tmp[0] = int(str(tmp[0])) 

    if tmp[0] > 0 and tmp[0] <=100:
        outMon[str(tmp[0])] = tmp[1].split() # 두번째 구문 구분
        print outMon[str(tmp[0])]
    else:
        print "wrong input"

print "ID".ljust(10), "name".ljust(20), "Power".rjust(10)
for x in outMon.keys(): # 뒤에 dictionary처럼 keys()를 붙이면 키형태로 반환
    print x.ljust(10), outMon[x][0].ljust(20), outMon[x][1].rjust(10)


영어 단어 맞추기(파일연동)

팀 : shelve라는 모듈을 이용하자. shelve 모듈은 파일과 연동되면 파일 자체를 해쉬형태(사전형)로 만들어준다.


↓ 영어단어맞추기(파일+)