# 파일 열기
score_file = open("score.txt", "w", encoding="utf8")
# 파일 쓰기
print("수학 : 0", file=score_file)
print("영어 : 50", file=score_file)
# 파일 닫기
score_file.close()
위의 py파일을 실행하면 파일이 생성된다.
자바의 nio API보다 더 편의성에 초점을 둔 거 같다.
내용에는 문자열들이 들어가 있음.
💡 파일 쓰기 옵션은 기존C에서 배웠던 것 처럼,
w
는 덮어쓰기,a
는 이어쓰기,r
은 읽기 전용임..그리고 파이썬에서도 외부 리소스를 사용했으면 무조건 리소스를 반환해야 한다.
score_file = open("score.txt", "a", encoding="utf8")
# write를 사용할때는 줄바꿈을 직접 작성해야 한다.
score_file.write("과학 : 80")
score_file.write("\\n코딩 : 100")
score_file.close()
이번엔 a
옵션과 write
메서드를 이용해봤다.
파일을 열면 문자열이 append된걸 볼 수 있다.
마지막으로 파일 읽기이다.
score_file = open("score.txt", "r", encoding="utf8")
print(score_file.read())
score_file.close()
한줄씩 읽고 싶다면 readline()
메서드를 이용한다. 이 메서드는 \\0
까지 읽고 파일 커서를 다음 줄레 위치시킨다.
score_file = open("score.txt", "r", encoding="utf8")
while True:
line = score_file.readline()
if not line:
break
print(line, end="")
score_file.close()
모든 라인을 리스트 형태로 저장할 수도 있다. 이때는 readlines()
메서드를 이용한다.