AI/Python
[Python] 10-1장 파일 다루기(open, close, read, write), 파일 모드(r, w, a, r+)
K_EY
2023. 4. 10. 16:25
실습용 텍스트 파일
- 메모장에 아래 내용 작성 후 바탕화면에 profile.txt로 저장하였다
홍길동 Korean
슈퍼맨 American
셜록 홈즈 British
파일 열기(open)
- 파일을 사용하려면 우선 파일을 열어야 함
- 파일 이름을 받아서 파일 객체를 생성한 후 반환
- 파일을 여는 데 실패하면 None 객체 반환
파일 객체 = open(파일이름, 파일모드)
# 바탕화면에 있는 profile.txt라는 이름의 파일을 읽기 모드로 열기
infile = open("infile = open("C:\\Users\\Desktop\\profile.txt", "r")
※ 파일 경로의 백슬래시 사용할 때는 반드시 \\ 두번 넣어줘야 함
파일 모드(r, w, a, r+)
"r" | 읽기 모드(read mode) | 파일의 처음부터 읽음 |
"w" | 쓰기 모드(write mode) | 파일의 처음부터 씀. 파일이 없으면 생성. 파일이 있으면 기존 내용 지워짐 |
"a" | 덧붙이기 모드(append mode) | 파일의 끝부터 씀. 파일이 없으면 생성. 파일이 있으면 기존 내용 이후부터 씀 |
"r+" | 읽기 & 쓰기 모드 | 파일을 읽고 씀. 모드 변경하려면 seek() 호출 |
파일 닫기(close)
- 파일과 관련된 작업이 모두 종료되면 파일 닫아야 함
- 파일 객체.close()를 호출하면 파일 닫힘
- 우리가 파일을 사용하면 다른 프로그램은 파일에 접근할 수 없으므로 사용이 끝나면 바로 닫는 것 추천
파일 객체.close()
infile = open("C:\\Users\\Desktop\\profile.txt", "w") # 파일 쓰기 모드로 엶
infile.close() # 파일 닫음
파일 읽기(read, readlines, readline)
- 파일 객체.read()
: 파일을 읽기 모드("r")로 연 후, 전체 텍스트를 읽을 때 사용
파일 객체 = open(파일이름, "r")
print(파일 객체.read())
infile = open("C:\\Users\\Desktop\\profile.txt", "r", encoding = "utf-8")
print(infile.read())
infile.close()
# 홍길동 Korean
# 슈퍼맨 American
# 셜록 홈즈 British
※ 파일 안에 한글이 있으면 파일을 열 때 encoding="utf-8"을 넣어줘야 제대로 인식됨
- 파일 객체.readlines()
: 파일에 저장된 각각의 모든 줄이 리스트 안에 저장됨
: 줄바꿈은 \n으로 표시됨
infile = open("C:\\Users\\Desktop\\profile.txt", "r", encoding = "utf-8")
print(infile.read()) # ['홍길동 Korean\n', '슈퍼맨 American\n', '셜록 홈즈 British']
infile.close()
- 파일 객체.read()
: 파일에서 한 번에 한 줄만 읽음
infile = open("C:\\Users\\Desktop\\profile.txt", "r", encoding = "utf-8")
print(infile.read())
infile.close()
# 홍길동 Korean
- 파일 객체.readline().rstrip()
: 줄의 맨 끝에 있는 줄바꿈 기호 삭제
# 파일에 몇 줄이 있는지 확인하고 모든 줄 출력
infile = open("C:\\Users\\Desktop\\profile.txt", "r", encoding = "utf-8")
line = infile.readline().rstrip()
while line != "":
print(line)
line = infile.readline().rstrip()
infile.close()
# 홍길동 Korean
# 슈퍼맨 American
# 셜록 홈즈 British
파일에 몇 줄이 있는지 확인하는 다른 방법
infile = open("C:\\Users\\Desktop\\profile.txt", "r", encoding = "utf-8")
for line in infile:
line = line.rstrip()
print(line)
infile.close()
# 홍길동 Korean
# 슈퍼맨 American
# 셜록 홈즈 British
파일 쓰기(write)
- 파일 객체.write(데이터)
: 파일을 쓰기 모드("w")로 연 후, 데이터를 쓸 때 사용
: 기존 내용 사라지고 처음부터 데이터 쓰임
파일 객체 = open(파일이름, "w")
파일 객체.write(데이터)
outfile = open("C:\\Users\\Desktop\\score.txt", "w", encoding = "utf-8")
outfile.write("홍길동 0점\n")
outfile.write("슈퍼맨 50점\n")
outfile.write("셜록 홈즈 100점\n")
outfile.close()
※ 줄바꿈을 하고 싶으면 마지막에 \n 삽입
바탕화면의 score.txt 파일 내용
홍길동 0점
슈퍼맨 50점
셜록 홈즈 100점
파일 덧붙이기
- 파일을 덧붙이기 모드("a")로 연 후, 데이터를 추가할 때 사용
- 쓰기 모드("w")로 열었을 때와 달리 기존 데이터 이후부터 데이터 추가 가능
파일 객체 = open(파일이름, "a")
파일 객체.write(데이터)
outfile = open("C:\\Users\\Desktop\\score.txt", "a", encoding = "utf-8")
outfile.write("김철수 25점\n")
outfile.write("스폰지밥 75점\n")
outfile.close()
바탕화면의 score.txt 파일 내용
홍길동 0점
슈퍼맨 50점
셜록 홈즈 100점
김철수 25점
스폰지밥 75점