# w 쓰기 모드 (처음부터 파일 덮어쓰기)
f = open("test.txt", "w")
f.write("hi\n")
f.close()
# a 추가 모드 (파일의 끝에 추가)
f = open("test.txt", "a")
f.write("bye\n")
f.write("hello\n")
f.close()
# r 읽기 모드
f = open("phones.txt", "r", encoding = "utf-8")
text = f.read() #전체 읽기
print(text)
line = f.readline() #한 줄씩 읽기
print(line)
lines = f.readlines() #여러 줄을 리스트로 읽기
print(lines)
for line in f: #반복문으로 읽기
print(line.strip()) #strip 줄 끝의 엔터 제거
f.close()
with open("phones.txt", "r", encoding = "utf-8") as f:
text = f.read()
print(text)
# 문제 : 속담 파일에서 단어를 분리하여 리스트로 만들기
#읽기모드로 파일 열기
f = open("proverbs.txt", "r")
#for문을 통해서 한 줄씩 읽기
for line in f:
line = line.strip()
print(line)
split_words = line.split()
print(split_words)
for word in split_words:
print(word)
f.close()
To embed this project on your website, copy the following code and paste it into your website's HTML: