f = open('test.txt', 'w')
f.write('test')
# 아래도 가능하다.
# print('I am print', 'Mike', file=f, sep='#')
f.close()
with open('test.txt', 'w') as f:
f.write('test\n')
####################################################################
with open('test.txt', 'r') as f:
all = f.read()
# f.read(2) # 2 bytes 만 읽어옴
print(all) # with 문 밖에서도 all 참조 가능 !!!
# 라인 단위로 읽기
with open('test.txt', 'r') as f:
while True:
line = f.readline().strip()
print(line)
if not line:
break
with open('robot.txt', 'r') as f:
lines: list[str] = f.readlines()
for l in lines:
print(l.strip())
####################################################################
# 쓰기 / 읽기 모드로 파일 열기
s = """\
AAA
BBB
CCC
DDD
"""
# 쓰고 나서 읽기
with open('test.txt', 'w+') as f:
f.write(s)
f.seek(0)
print(f.read())
# 읽고 나서 쓰기
with open('test.txt', 'r+') as f:
print(f.read())
f.write(s)