[Python] 파일 입출력

1 minute read

[Python] 다양한 출력 포맷Permalink

Inflearn StudyPermalink

링크: https://www.inflearn.com/

  • 인프런에서 “파이썬 무료 강의 (기본편) - 6시간 뒤면 나도 개발자” 강의를 들으며 혼자 공부한 내용입니다.

파일 입출력Permalink

1) 파일 열기

score_file = open("score.txt", "w", encoding="utf8") 
  • open(“파일명”, “명령어”, encoding=”utf8”)
    • 명령어
      • w : 덮어쓰기
      • a : 이어쓰기
      • r : 읽기
    • utf8: 한글을 읽기 위해 사용

2) 파일 닫기

score_file.close()

3) 파일 내용 쓰기

score_file = open("score.txt", "w", encoding="utf8") # 한글을 위해
print("수학 : 0", file=score_file)
print("영어 : 50", file=score_file)
score_file.close()
  • 명령어가 w 이므로 score.txt라는 파일에 내용을 덮어 씁니다.
  • print문을 이용해 파일 내용을 쓰면 자동으로 줄바꿈을 합니다.
score_file = open("score.txt", "a", encoding="utf8")
score_file.write("과학 : 80\n")
score_file.write("코딩 : 100")
score_file.close()
  • 명령어가 a 이므로 score.txt라는 파일에 내용을 이어 씁니다.
  • write를 이용하여 파일 내용을 쓰면 자동으로 줄바꿈이 이루어지지 않으므로 \n을 따로 적어줘야합니다.

4) 파일 내용 읽기

  • read() : 파일의 모든 내용을 읽습니다.
score_file = open("score.txt", "r", encoding="utf8")
print(score_file.read())
score_file.close()
  • readline(): 한 줄씩 읽고 커서는 다음 줄로 이동합니다.
score_file = open("score.txt", "r", encoding="utf8")
print(score_file.readline(), end="") # 줄별로 읽고 커서는 다음줄로 이동
print(score_file.readline(), end="") # 줄별로 읽고 커서는 다음줄로 이동
print(score_file.readline(), end="") # 줄별로 읽고 커서는 다음줄로 이동
print(score_file.readline(), end="") # 줄별로 읽고 커서는 다음줄로 이동
score_file.close()
  • 파일의 줄 개수를 모를 때 무한 반복문(while True)을 이용하여 읽습니다.
score_file = open("score.txt", "r", encoding="utf8")
while True:
    line = score_file.readline() # 한 줄씩 읽습니다.
    if not line: # 읽을 줄이 없는 경우
        break # 반복문 탈출
    print(line)

score_file.close()
  • 파일의 줄 개수를 모를 때 list를 이용하여 읽습니다.
score_file = open("score.txt", "r", encoding="utf8")
lines = score_file.readlines() # list 형태로 저장
for line in lines:
    print(line, end="")

score_file.close()

Leave a comment