import os print os.getcwd() 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 f = open('t.txt') i = 1 for line in f: print i, ":", line, i += 1 f.close() f = open('t.txt') line = f.readline() i = 1 while line: print i, ":", line, line = f.readline() i += 1 f.close() 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() f = open('t.txt') print f print f.xreadlines() print f.seek(0) i = 1 for line in f.xreadlines(): print i, ":", line, i += 1 f.close() lines = ['first line\n', 'second line\n', 'third line\n'] f = open('t1.txt', 'w+') f.writelines(lines) f.seek(0) print f.read() f.close() lines = ['first line\n', 'second line\n', 'third line\n'] f = open('t1.txt', 'w') f.write(''.join(lines)) f = open('t1.txt') #읽기 print f.read() print f.read() f.close() lines = ['first line', 'second line', 'third line'] f = open('t1.txt', 'w+') f.write('\n'.join(lines)) f.seek(0) print f.read() f.close() f = open('t.txt') s = f.read() n = len(s.split()) print n f.close() n = len(open('t.txt').read().split()) print n f = open('t.txt') s = f.read() print s.count('\n') f.close() f = open('t.txt') print len(f.readlines()) f.close() print len(open('t.txt').readlines()) print open('t.txt').read().count('\n') f = open('t.txt') print len(f.read()) import os os.path.getsize('t.txt') import os os.linesep f = open('t.txt') f.read(10) f.read(10) 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() 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 f.seek(2, 1) # 현재 위치에서 2바이트 포인터 이동 print f.tell() print f.read(1) print f.seek(-3,2) # 끝부터 앞으로 3바이트 포인터 이동 print f.tell() print f.read(1) name = 't.txt' f = open(name, 'w+') s = '0123456789abcdef' f.write(s) f.seek(0) f.truncate(10) # 현재 포인터 위치에서 10 바이트 이후를 잘라 버림 f.seek(0) print f.read() print f.seek(5) f.truncate() # 현재 포인터 위치에서 마지막까지 잘라 버림 f.seek(0) print f.read() name = 't.txt' f = open(name, 'w+') print f.closed print f.mode print f.name #filename: replace.py #coding=utf-8 import sys # argv 처리를 위해 필요함 import re # 정규식 처리를 위해 필요함 def replace(fname, srcstr, deststr): f = open(fname) txt = f.read() txt = re.subn(srcstr, deststr, txt)[0] return txt if __name__ == '__main__': if len(sys.argv) != 4: print """Usage : replace filename srcstr deststr""" sys.exit() print replace(sys.argv[1], sys.argv[2], sys.argv[3]) # redirect.py 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() print >> sys.stderr, "Warning, action field not supplied" f = open('t.txt', 'w+') print >> f, 'spam string' f.seek(0) print f.read() f.close() import StringIO f = StringIO.StringIO() f.write("abc") f.seek(0) s = f.read() print s print s2 = f.getvalue() print s2 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 # stringfile.py import StringIO s = '''Python is a coollittle language. It is well designed, compact, easy to learn and fun to program in. Python strongly encourages the programmer to program in an OO-way, but does not require it. ''' f = StringIO.StringIO(s) #문자열 객체에서 파일 객체 얻어 내기 f.read().upper() #대문자로 변환 import anydbm f = anydbm.open('music', 'n') f['flute'] = 'wood wind' f['violin'] = 'string' f['piano'] = 'keyboard' print f.keys() # keys() 메소드 print f.values() print f.items() print print len(f) # 레코드 수 print print 'oboe' in f # 멤버십 테스트 print print f['flute'] # 인덱싱으로 값 읽어오기 print f['violin'] f.close() # 파일 닫기 import anydbm f = anydbm.open('music','c') #'music' 파일 열기 print f.keys() #키 목록 얻기 print for k in f: #전체 내용 출력 print k, '-', f[k] f.close() import anydbm f = anydbm.open('music','c') # 'music' 파일 열기 f['oboe'] = 'wood wind' # 내용 추가 f['piano'] = 'keyboard instrument' # 내용 변경 del f['violin'] # 내용 삭제 for k in f: print k, '-', f[k] # 다시 전체 내용 출력 f.close() 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 # 리스트 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