본문으로 바로가기

파일 입출력

category onYouTube/Python 2021. 3. 14. 13:41
  • open(" ", 'd') : d의 형태 파일 생성
  • close( ) : 파일 종료

 

  • w : 쓰기 모드; 이미 존재하는 파일을 열면 기존의 내용이 모두 삭제됨
  • a : 추가 모드
  • r : 읽기 모드

 

  • readline( ) : 파일의 내용 한 줄씩 읽기
  • read( ) : 파일의 내용 전체 읽기
  • write( ) : 파일에 내용 추가하기

score_file = open("score.txt", 'w', encoding="utf8")
print("수학 : 0", file=score_file)
print("영어 : 50", file=score_file)
score_file.close()

score_file = open("score.txt", 'a', encoding="utf8")
score_file.write("과학 : 80")
score_file.write("\n코딩 : 100")
score_file.close()

score_file = open("score.txt", "r", encoding="utf8")
print(score_file.read())
score_file.close()

score_file = open("score.txt", "r", encoding="utf8")
print(score_file.readline()) # 한 줄 읽고 다음 줄로 커서 이동; 자동 개행
print(score_file.readline(), end="") # 자동 개행 없이 한 줄 읽기
score_file.close()

# 파일이 총 몇 줄인지 모를 때 반복문 사용해서 파일 전체 읽기
score_file = open("score.txt", "r", encoding="utf8")
while True:
    line = score_file.readline()
    if not line:
        break
    print(line, end="")
score_file.close()

score_file = open("score.txt", "r", encoding="utf8")
lines = score_file.readlines() # list 형태로 저장
for line in lines:
    print(line, end="")

 

 

-출처-

www.youtube.com/watch?v=kWiCuklohdY&t=10728s

'onYouTube > Python' 카테고리의 다른 글

With  (0) 2021.03.14
Pickle  (0) 2021.03.14
다양한 출력 포맷  (0) 2021.03.14
표준 입출력  (0) 2021.03.14
집합  (0) 2021.03.14