Mode | 간단 설명 | 자세한 설명 |
---|---|---|
'r' | 읽기 전용 (기본 모드) | 파일 객체를 읽기 모드로 생성하고, 파일 포인터를 파일 처음 위치에 놓는다. |
'w' | 쓰기 전용 | 새로운 파일을 쓰기 모드로 생성하거나 해당 파일이 이미 존재하면 내용을 모두 없에면서 쓰기 모드로 생성하고, 파일 포인터를 파일 처음 위치에 놓는다. |
'a' | 파일 끝에 추가 | 이미 존재하는 파일을 쓰기 모드로 생성하거나 파일이 존재하지 않으면 새롭게 파일을 생성하면서 쓰기 모드로 생성하고, 파일 포인터를 파일의 마지막 위치에 놓는다. 따라서, 이후 작성되는 내용은 파일의 뒷 부분에 추가된다. |
Mode | 간단 설명 |
---|---|
'rb' | 이진 파일 읽기 전용 |
'wb' | 이진 파일 쓰기 전용 |
'ab' | 이진 파일 끝에 추가 |
import os
print(os.getcwd())
/Users/jubong/git/python-link-e-learning/python3.6
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)
print(type(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. <class 'str'>
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."""
with open('t.txt', 'w') as f:
f.write(s) # 문자열을 파일에 기록
with open('t.txt', 'r') as f:
s = f.read()
print(s)
print(type(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. <class 'str'>
f = open('t.txt')
for i, line in enumerate(f):
print(i+1, ":", line, end="")
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()
print(type(line))
i = 1
while line:
print(i, ":", line, end="")
line = f.readline()
i += 1
f.close()
<class 'str'> 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(type(f.readlines()))
print()
f.seek(0)
i = 1
for line in f.readlines():
print(i, ":", line, end="")
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.'] <class 'list'> 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(type(f.readlines()))
print()
f.close()
f = open('t.txt')
i = 1
for line in f.readlines():
print(i, ":", line, end="")
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.'] <class 'list'> 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()
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-10-58fb3beae1a7> in <module> 1 f = open('t.txt') ----> 2 print(f.xreadlines()) 3 print() 4 5 f.seek(0) AttributeError: '_io.TextIOWrapper' object has no attribute 'xreadlines'
lines = ['first line\n', 'second line\n', 'third line\n']
f = open('t1.txt', 'w')
f.writelines(lines)
f.close()
f = open('t1.txt')
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')
print(f.read())
f.close()
first line second line third line
f = open('t.txt')
s = f.read()
print(s)
n = len(s.split())
print(n)
f.close()
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. 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())
f.close()
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 # 파일 객체로 표준 출력 변경
stdout.write("!!!!!!")
print('Sample output')
print('Good')
print('Good')
f.close()
sys.stdout = stdout # 표준 출력 원상 복구
!!!!!!
f = open('t.txt')
print(f.read())
Sample output Good Good
print("Hello koreatech!", file=open("output.txt", "w"))
f = open('output.txt')
print(f.read())
Hello koreatech!
print >> sys.stderr, "Warning, action field not supplied"
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-21-3654042ca1da> in <module> ----> 1 print >> sys.stderr, "Warning, action field not supplied" TypeError: unsupported operand type(s) for >>: 'builtin_function_or_method' and 'OutStream'. Did you mean "print(<message>, file=<output_stream>)"?
print("Warning, action field not supplied", file=sys.stderr)
Warning, action field not supplied
f = open('t.txt', 'w')
print('spam string', file=f)
f.close()
f = open('t.txt')
print(f.read())
f.close()
spam string
import sys
from io import StringIO
f = StringIO()
f.write("abc")
f.write("def")
q = f.read()
print(q)
q1 = f.getvalue()
print(q1)
abcdef
f.seek(2)
print(f.read())
f.close()
cdef
def f1():
s = ""
for i in range(10000, 1000000):
s += str(i)
def f2():
s = StringIO()
for i in range(10000, 1000000):
s.write(str(i))
%timeit f1()
300 ms ± 9.37 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit f2()
262 ms ± 14 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
import sys
from io import StringIO
stdout = sys.stdout # 표준 출력 저장해 두기
sys.stdout = f = StringIO()
print(type(f))
print('Sample output')
print('Good')
print('Good')
sys.stdout = stdout
s = f.getvalue()
print('Done-------')
print(s)
Done------- <class '_io.StringIO'> Sample output Good Good
import pickle
phone = {'tom':4358382, 'jack':9465215, 'jim':6851325, 'Joseph':6584321}
List = ['string', 1234, 0.2345]
Tuple = (phone, List) # 리스트, 튜플, 사전의 복합 객체
with open('pickle.txt', 'wb') as f: # 파일 객체를 얻는다.
pickle.dump(Tuple, f) # 파일로 출력(pickling), 복합 객체 출력
with open('pickle.txt', 'rb') as f:
x,y = pickle.load(f) # 파일에서 읽어오기. 튜플의 내용을 x, y에 받는다.
print(x) # 사전
print(y) # 리스트
{'tom': 4358382, 'jack': 9465215, 'jim': 6851325, 'Joseph': 6584321} ['string', 1234, 0.2345]
import pickle
class Simple: # 가장 단순한 클래스를 정의
pass
s = Simple() # 인스턴스 객체 생성
s.count = 10 # 인스턴스 이름 공간에 변수 생성
with open('pickle2.txt', 'wb') as f:
pickle.dump(s, f) # 인스턴스 저장
with open('pickle2.txt', 'rb') as f:
t = pickle.load(f) # 인스턴스 가져오기
print(t.count)
10
Mode | 간단 설명 | 자세한 설명 |
---|---|---|
'r' | 읽기 전용(기본 모드) | 파일 객체를 읽기 모드로 생성하고, 파일 포인터를 파일 처음 위치에 놓는다. |
'w' | 쓰기 전용(기존 파일 내용 삭제) | 파일이 존재하지 않으면 새로운 파일을 쓰기 모드로 생성하고, 해당 파일이 이미 존재하면 내용을 모두 없에면서 쓰기 모드로 생성하고, 파일 포인터를 파일 처음 위치에 놓는다. |
'a' | 파일 끝에 추가(쓰기 전용) | 파일이 존재하지 않으면 새롭게 파일을 생성하면서 쓰기 모드로 생성하고, 해당 파일이 이미 존재하면 파일 객체을 쓰기 모드로 생성하면서 파일 포인터를 파일의 마지막 위치에 놓는다. 따라서, 이후 작성되는 내용은 파일의 뒷 부분에 추가됨. |
'r+' | 읽고 쓰기 | 파일 객체를 읽고 쓸 수 있도록 생성한다. 파일 포인터를 파일 처음 위치에 놓는다. |
'w+' | 읽고 쓰기(기존 파일 내용 삭제) | 파일 객체를 읽고 쓸 수 있도록 생성한다. 파일이 존재하지 않으면 새로운 파일을 생성하고, 해당 파일이 이미 존재하면 내용을 모두 없에면서 생성하고, 파일 포인터를 파일 처음 위치에 놓는다. |
'a+' | 읽고 쓰기(파일 끝에 추가) | 파일 객체를 읽고 쓸 수 있도록 생성한다. 파일이 존재하지 않으면 새롭게 파일을 생성하고, 해당 파일이 이미 존재하면 파일 객체을 생성하면서 파일 포인터를 파일의 마지막 위치에 놓는다 (그래서, 이후 작성되는 내용은 파일의 뒷 부분에 추가). |
Mode | 간단 설명 |
---|---|
'rb' | 이진 파일 읽기 전용 |
'wb' | 이진 파일 쓰기 전용(기존 파일 내용 삭제) |
'ab' | 이진 파일 끝에 추가(쓰기 전용) |
'rb+' | 이진 파일 읽고 쓰기 |
'wb+' | 이진 파일 읽고 쓰기(기존 파일 내용 삭제) |
'ab+' | 이진 파일 끝에 추가(읽기도 가능) |
참고 문헌: 파이썬(열혈강의)(개정판 VER.2), 이강성, FreeLec, 2005년 8월 29일