관리 메뉴

엘리

파이썬_파일 입출력_나도코딩님 강의 본문

프로그래밍 공부 일지/파이썬 공부

파이썬_파일 입출력_나도코딩님 강의

엘리허 2021. 7. 28. 06:41

#파일 입력

score_file=open("score.txt",'w',encoding="utf8") #오픈을 이용해서 파일을 열수 있음

# W 이 파일을 쓰기 위한 목적

#encoding="utf8" 한글을 썼을때 이상하게 적히는 경우가 있다.

print("수학:0",file=score_file)

print("영어:50",file=score_file)

score_file.close() #반드시 닫아줘야 함

 

#이어쓰기

score_file=open("score.txt","a",encoding="utf8"

 

# a : 이 파일에 이어 쓰겠다!

score_file.write("과학:80")

score_file.write("\n코딩:100")

score_file.close()

 

#불러오기

score_file=open("score.txt","r",encoding="utf8") #r은 read의 뜻

print(score_file.read()) #모든내용을 다 읽어온다 read을 쓴다면!

score_file.close()

 

#한줄씩 불러오기

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

print(score_file.readline()) #줄별로 읽기, 한 줄 읽고 커서는 다음 줄로 이동

print(score_file.readline()) #줄바꿈을 원하지 않으면 뒤에 ,end =""

print(score_file.readline())

print(score_file.readline())

score_file.close()

 

#총 몇줄인줄 모를때 처리하는 방법 반복문을 통해서 파일의 내용을 불러 올수 있음

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

while True:

line=score_file.readline()

if not line:

break

print(line)

score_file.close()

 

#리스트에 값을 넣어서 처리 가능

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

lines=score_file.readlines() #모든 라인을 가지고 와서 리스트 형태로 저장함

for line in lines:

print(line, end="")

score_file.close()

 

나도코딩님 강의 따라 쓰기만 했는데

이해가 쏙쏙 되구만 :)

오늘도 감사합니다!

 

#나도코딩

#이해쏙쏙강의

#감사합니당