본문 바로가기
코딩(개발)/파이썬

파이썬 파일 입출력

by 플랜데버 2020. 12. 20.

공부하는게 취미인 사람들 투딩


#파일 입출력

 

#파일 생성하기

코드
score_file = open("score.txt", "w" , encoding="utf-8") #파일명 , 쓰기위한 목적 , 한글쓰기 위해
print("수학:0",file=score_file)
print("영어:50",file=score_file)
score_file.close()

 

#파일 내용 더하기

코드
score_file = open("score.txt", "a" , encoding="utf-8") # a : 덮어쓰기
score_file.write("과학 : 80")
score_file.write("\n코딩 : 100") #줄바꿈 써줘야 된다.
score_file.close()

 

#파일 읽기 (한꺼번에 모두 읽기)

코드
score_file = open("score.txt""r" , encoding="utf-8"# r : 파일 읽기
print(score_file.read())
score_file.close()

 

#파일 읽기 (각각 읽고 출력)

코드
score_file = open("score.txt""r" , encoding="utf-8"# r : 파일 읽기
print(score_file.readline() , end=""#줄별로 읽기 , 한줄 읽고 커서는 다음 줄로 이동print(score_file.readline() , end="")
print(score_file.readline() , end="")
print(score_file.readline() , end="")
score_file.close()

 

#총 몇줄인지 모를때

코드

score_file = open("score.txt""r" , encoding="utf-8"# r : 파일 읽기

while True:

    line = score_file.readline()

    if not line:

        break

    print(line , end="")

score_file.close()    

 

 

#리스트에 넣어서 읽기

코드
score_file = open("score.txt", "r" , encoding="utf-8") # r : 파일 읽기
lines = score_file.readlines() #list 형태로 저장
for line in lines:
    print(line , end="")
score_file.close() 

 

 

 

 

더보기

블로그에는 우클릭 방지가 걸려있어요. 코드복사는 카페에서 가능 합니다.

투딩카페의 이 컨텐츠보기

중간중간 제 생각이 첨삭된 부분이 있습니다. 실제 강의는 선생님걸로 들으세요~

파이썬 기초는 나도코딩님이 인프런사이트에서 강의한 내용을 바탕으로 공부한 내용을 정리한 것 입니다.

추천 :  ★

 

목소리 : 

속도 :

내용 : 

결과물 :

 

 

'코딩(개발) > 파이썬' 카테고리의 다른 글

파이썬 예외처리  (0) 2020.12.22
파이썬 class  (0) 2020.12.21
파이썬 표준 입출력  (0) 2020.12.20
파이썬 함수 문제 풀기  (0) 2020.12.20
파이썬 가변 인자 / 글로벌 변수  (0) 2020.12.19

댓글