import os
print os.getcwd()
/Users/yhhan/git/ipython
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 : 2 : Its power: Python developers typically report 3 : they are able to develop applications in a half 4 : to a tenth the amount of time it takes them to do 5 : 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 : 2 : Its power: Python developers typically report 3 : they are able to develop applications in a half 4 : to a tenth the amount of time it takes them to do 5 : 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()
['\n', '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.\n'] 1 : 2 : Its power: Python developers typically report 3 : they are able to develop applications in a half 4 : to a tenth the amount of time it takes them to do 5 : the same work in such languages as C.
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()
<open file 't.txt', mode 'r' at 0x10b9058a0> <open file 't.txt', mode 'r' at 0x10b9058a0> 1 : 2 : Its power: Python developers typically report 3 : they are able to develop applications in a half 4 : to a tenth the amount of time it takes them to do 5 : the same work in such languages as C.
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()
first line second line third line
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()
first line second line third line
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()
first line second line third line
f = open('t.txt')
s = f.read()
n = len(s.split())
print n
f.close()
35
n = len(open('t.txt').read().split())
print n
35
f = open('t.txt')
s = f.read()
print s.count('\n')
f.close()
5
f = open('t.txt')
print len(f.readlines())
f.close()
5
print len(open('t.txt').readlines())
5
print open('t.txt').read().count('\n')
5
f = open('t.txt')
print len(f.read())
184
import os
os.path.getsize('t.txt')
184
import os
os.linesep
'\n'
f = open('t.txt')
f.read(10)
'\nIts power'
f.read(10)
': Python d'
Mode | 간단 설명 | 자세한 설명 |
---|---|---|
'r' | 읽기 전용(기본 모드) | Open text file for reading. The stream is positioned at the beginning of the file. |
'w' | 쓰기 전용(기존 파일 내용 삭제) | Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file. |
'a' | 파일 끝에 추가(쓰기 전용) | Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file. |
'r+' | 읽고 쓰기 | Open for reading and writing. The stream is positioned at the beginning of the file. |
'w+' | 읽고 쓰기(기존 파일 내용 삭제) | Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file. |
'a+' | 파일 끝에 추가(읽기도 가능) | Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file. |
Mode | 간단 설명 |
---|---|
'rb' | 이진 파일 읽기 전용 |
'wb' | 이진 파일 쓰기 전용(기존 파일 내용 삭제) |
'ab' | 이진 파일 끝에 추가(쓰기 전용) |
'rb+' | 이진 파일 읽고 쓰기 |
'wb+' | 이진 파일 읽고 쓰기(기존 파일 내용 삭제) |
'ab+' | 이진 파일 끝에 추가(읽기도 가능) |
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
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)
5 5 6 8 8 13 d
메소드 | 간단 설명 |
---|---|
file.flush() | 버퍼의 내용을 모두 파일에 출력한다. |
file.fileno() | file 객체의 파일 기술(File Descriptor)를 리턴한다. |
file.isatty() | 만일 file 객체가 tty 장치이면 True, 아니면 False을 리턴한다. |
file.truncate([size]) | 파일을 현재 포인터 위치부터 지정된 바이트 크기 이후를 버림. 인수를 주지 않으면 마지막까지 자른다. |
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()
0123456789 01234
메소드 | 간단 설명 |
---|---|
file.closed | closed되었으면 True, 아니면 False을 리턴한다. |
file.mode | 파일이 오픈된 모드 |
file.name | 오픈된 파일 이름 |
name = 't.txt'
f = open(name, 'w+')
print f.closed
print f.mode
print f.name
False w+ t.txt
Do you work in C, C++, or Java on large projects? We'll show how Python will give you results quicker and more reliably. Are you already scripting in a laguage other than Python? Whatever programming you're doing now, Python can improve it.
#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])
> ipython replace.py sample.txt show SHOW
Do you work in C, C++, or Java on large projects? We'll SHOW how Python will give you results quicker and more reliably. Are you already scripting in a laguage other than Python? Whatever programming you're doing now, Python can improve it.
> ipython replace.py sample.txt [a-z] ""
D C, C++, J ? W' P . A P? W ' , P .
> ipython replace.py sample.txt \W ^
Do^you^work^in^C^^C^^^^or^Java^on^large^projects^^We^ll^show^how^Python^will^give^you^results^quicker^and^more^reliably^^Are^you^already^scripting^in^a^laguage^other^than^Python^^Whatever^programming^you^re^doing^now^^Python^can^improve^it^
# 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()
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.seek(0)
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
# 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() #대문자로 변환
'PYTHON IS A COOLLITTLE LANGUAGE.\nIT IS WELL DESIGNED, COMPACT, EASY TO LEARN AND FUN TO PROGRAM IN.\nPYTHON STRONGLY ENCOURAGES THE PROGRAMMER TO PROGRAM IN AN OO-WAY,\nBUT DOES NOT REQUIRE IT.\n'
mode | 간단 설명 |
---|---|
'r' | 읽기 전용 모드로 오픈 (기본값) |
'w' | 읽기/쓰기 모드로 오픈 |
'c' | 읽기/쓰기 모드로 오픈, 파일이 없으면 생성 |
'n' | 읽기/쓰기 모드로 오픈, 항상 새로운 내용으로 초기화하여 오픈 |
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() # 파일 닫기
['flute', 'piano', 'violin'] ['wood wind', 'keyboard', 'string'] [('flute', 'wood wind'), ('piano', 'keyboard'), ('violin', 'string')] 3 False wood wind string
import anydbm
f = anydbm.open('music','c') #'music' 파일 열기
print f.keys() #키 목록 얻기
print
for k in f: #전체 내용 출력
print k, '-', f[k]
f.close()
['flute', 'piano', 'violin'] flute - wood wind piano - keyboard violin - string
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()
flute - wood wind oboe - wood wind piano - keyboard instrument
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