Mode | 간단 설명 | 자세한 설명 |
---|---|---|
'r' | 읽기 전용 (기본 모드) | 파일 객체를 읽기 모드로 생성하고, 파일 포인터를 파일 처음 위치에 놓는다. |
'w' | 쓰기 전용 | 새로운 파일을 쓰기 모드로 생성하거나 해당 파일이 이미 존재하면 내용을 모두 없에면서 쓰기 모드로 생성하고, 파일 포인터를 파일 처음 위치에 놓는다. |
'a' | 파일 끝에 추가 | 이미 존재하는 파일을 쓰기 모드로 생성하거나 파일이 존재하지 않으면 새롭게 파일을 생성하면서 쓰기 모드로 생성하고, 파일 포인터를 파일의 마지막 위치에 놓는다. 그래서, 이후 작성되는 내용은 파일의 뒷 부분에 추가된다. |
Mode | 간단 설명 |
---|---|
'rb' | 이진 파일 읽기 전용 |
'wb' | 이진 파일 쓰기 전용 |
'ab' | 이진 파일 끝에 추가 |
import os
print os.getcwd()
/Users/yhhan/git/python-e-learning
s = """Its power: Python developers typically report
they are able to develop applications in a half
to a tenth the amount of time it takes them to do
the same work in such languages as C."""
f = open('t.txt', 'w')
f.write(s) # 문자열을 파일에 기록
f.close()
f = file('t.txt') # f = open('t.txt', 'r')과 동일
s = f.read()
print s
Its power: Python developers typically report they are able to develop applications in a half to a tenth the amount of time it takes them to do the same work in such languages as C.
f = open('t.txt')
i = 1
for line in f:
print i, ":", line,
i += 1
f.close()
1 : Its power: Python developers typically report 2 : they are able to develop applications in a half 3 : to a tenth the amount of time it takes them to do 4 : the same work in such languages as C.
f = open('t.txt')
line = f.readline()
i = 1
while line:
print i, ":", line,
line = f.readline()
i += 1
f.close()
1 : Its power: Python developers typically report 2 : they are able to develop applications in a half 3 : to a tenth the amount of time it takes them to do 4 : the same work in such languages as C.
f = open('t.txt')
print f.readlines()
print
f.seek(0)
i = 1
for line in f.readlines():
print i, ":", line,
i += 1
f.close()
['Its power: Python developers typically report \n', 'they are able to develop applications in a half\n', 'to a tenth the amount of time it takes them to do\n', 'the same work in such languages as C.'] 1 : Its power: Python developers typically report 2 : they are able to develop applications in a half 3 : to a tenth the amount of time it takes them to do 4 : the same work in such languages as C.
f = open('t.txt')
print f.xreadlines()
print
f.seek(0)
i = 1
for line in f.xreadlines():
print i, ":", line,
i += 1
f.close()
<open file 't.txt', mode 'r' at 0x10ddbfa50> 1 : 0123456789abcdef
lines = ['first line\n', 'second line\n', 'third line\n']
f = open('t1.txt', 'w')
f.writelines(lines)
f.close()
f = open('t1.txt')
f.seek(0)
print f.read()
f.close()
first line second line third line
lines = ['first line', 'second line', 'third line']
f = open('t1.txt', 'w')
f.write('\n'.join(lines))
f.close()
f = open('t1.txt')
f.seek(0)
print f.read()
f.close()
first line second line third line
f = open('t.txt')
s = f.read()
n = len(s.split())
print n
f.close()
35
f = open('removeme.txt', 'w') # 파일의 생성
f.write('first line\n')
f.write('second line\n')
f.close()
f = open('removeme.txt', 'a') # 파일 추가 모드로 오픈
f.write('third line\n')
f.close()
f = open('removeme.txt') # 파일 읽기
print f.read()
first line second line third line
name = 't.txt'
f = open(name, 'w+') # 읽고 쓰기로 오픈, 단, 파일이 이미 존재한다면 기존 파일은 없어지고 다시 생성된다.
s = '0123456789abcdef'
f.write(s)
f.seek(5) # 시작부터 5바이트 포인터 이동
print f.tell() # 현재 위치 돌려줌
print f.read(1) # 1문자 읽기
print f.tell()
print
5 5 6
import sys
f = open('t.txt', 'w')
stdout = sys.stdout # 표준 출력 저장해 두기
sys.stdout = f # 파일 객체로 표준 출력 변경
print 'Sample output'
print 'Good'
print 'Good'
f.close()
sys.stdout = stdout # 필요하면 표준 출력 원상 복구
f = open('t.txt')
print f.read()
Sample output Good Good
print >> sys.stderr, "Warning, action field not supplied"
Warning, action field not supplied
f = open('t.txt', 'w')
print >> f, 'spam string'
f.close()
f = open('t.txt')
print f.read()
f.close()
spam string
import StringIO
f = StringIO.StringIO()
f.write("abc")
f.seek(0)
s = f.read()
print s
print
s2 = f.getvalue()
print s2
abc abc
import sys
import StringIO
stdout = sys.stdout # 표준 출력 저장해 두기
sys.stdout = f = StringIO.StringIO()
print type(f)
print 'Sample output'
print 'Good'
print 'Good'
sys.stdout = stdout
s = f.getvalue()
print 'Done-------'
print s
Done------- <type 'instance'> Sample output Good Good
import pickle
phone = {'tom':4358382, 'jack':9465215, 'jim':6851325, 'Joseph':6584321}
List = ['string', 1234, 0.2345]
Tuple = (phone, List) # 리스트, 튜플, 사전의 복합 객체
f = open('pickle.txt', 'w') # 파일 객체를 얻는다.
pickle.dump(Tuple, f) # 파일로 출력(pickling), 복합 객체 출력
f.close()
f = open('pickle.txt')
x,y = pickle.load(f) # 파일에서 읽어오기. 튜플의 내용을 x, y에 받는다.
print x # 사전
print y # 리스트
{'jim': 6851325, 'Joseph': 6584321, 'jack': 9465215, 'tom': 4358382} ['string', 1234, 0.2345]
import pickle
class Simple: # 가장 단순한 클래스를 정의
pass
s = Simple() # 인스턴스 객체 생성
s.count = 10 # 인스턴스 이름 공간에 변수 생성
f = open('pickle2.txt', 'w')
pickle.dump(s, f) # 인스턴스 저장
f.close()
f = open('pickle2.txt')
t = pickle.load(f) # 인스턴스 가져오기
print t.count
10
참고 문헌: 파이썬(열혈강의)(개정판 VER.2), 이강성, FreeLec, 2005년 8월 29일