Pythonic - 핸들링
· 약 4분
파일
- File pointer 여는 법은
f.open(‘test.txt’, ‘w’)
- 이 경우 f.write 후에 f.close 해줘야한다.
with
사용시 close 를 생각하지 않아도 된다.with
구문에서 선언된 변수는 바깥에서 사용가능f.seek(5)
처럼 위치로 이동 가능하다.string.Template
과 함께 뷰 파일에서 사용할 수 있다.
# 예시 1
with open('test.txt', 'w') as f:
f.write('Test')
# 예시 2
with open('test.txt', 'r') as f:
# print(f.read())
while True:
chunk = 2
line = f.read(chunk)
print(line)
if not line:
reak
# 예시 3
# w+ 로 열면 파일이 초기화 됨
with open('test.txt', 'w+') as f:
f.write(s)
# 쓰기 후에 읽기위해 0번째로 이동
f.seek(0)
print(f.read())
# 예시 4
import string
with open('view/mail.tpl', 'r') as f:
t = string.Template(f.read())
# $name, $contents
contents = t.substitute(name='gracefullight', contents='Thanks')
print(contents)