유튜브 '나도코딩'채널의 파이썬 강좌를 토대로 정리한 내용입니다.

파일 입출력

1. w(write) : 덮어쓰기

입력

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

출력

score.txt 라는 새로운 텍스트파일이 생성된다.

2. a(append) : 이어쓰기

입력

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

출력

"a" append를 통해 과학과 코딩의 값이 추가 된 것을 확인할 수 있다.

3. r(read) : 읽어오기

입력

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

출력

수학 : 0
영어 : 50
과학 : 80
코딩 : 100

터미널창에 score.txt안의 자료가 읽어오기가 되어 출력된 모습이다.

4. 줄별로 읽기, 한 줄 읽고 커서는 다음 줄로 이동

입력

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

출력

수학 : 0
...
영어 : 50
...
과학 : 80
...
코딩 : 100

5. file에서 자료를 가져오는데 몇 줄이 있는지 모르는 상황에서 조건문을 활용하여 마지막까지 읽어드린다.

입력

score_file = open("score.txt", "r", encoding="utf8")
while True:
	line = score_file.readline()
    if not line:
    	break
    print(line)
score_file.close()

출력

수학 : 0
...
영어 : 50
...
과학 : 80
...
코딩 : 100

6. score_file 자료를 list형태로 읽어오기

입력

score_file = open("score.txt", "r", encoding="utf8")
line = score_file.readlines()
for line in lines:
	print(line)
score_file.close()
print(type(lines))

출력

수학 : 0
...
영어 : 50
...
과학 : 80
...
코딩 : 100
<class 'list'>

0개의 댓글

Powered by GraphCDN, the GraphQL CDN