====== 파일 읽기, 쓰기 ====== * description : 파일 읽기, 쓰기 * author : 도봉산핵주먹 * email : hylee@repia.com * lastupdate : 2020-06-25 ===== 파일 읽기, 쓰기 ===== > 현재 진행중인 프로젝트 안에 참조할 파일을 만든 뒤 진행하시면 됩니다.\\ > 파일 쓰기 예제는 콘솔에 써진 파일 내용을 출력해 놨으니 콘솔로 확인하시면 됩니다.\\ ==== 준비 사항 ==== === 참조 폴더와 파일 만들기 === {{:wiki:ai:python:pkgpng2.png?direct&400|}} ==== 파일 내용 ==== === review.txt === The film, projected in the form of animation, imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues, which eventually paves the path for gaining a fresh perspective on an age-old problem. The story also happens to centre around two parallel characters, Shundi King and Hundi King, who are twins, but they constantly fight over unresolved issues planted in their minds by external forces from within their very own units. === score.txt === 95 78 92 89 100 66 ==== 예제 코드 ==== # Section09 # 파일 읽기, 쓰기 # 읽기 모드 r, 쓰기 모드(기존 파일 삭제) w, 추가 모드(파일 생성 또는 추가) a # 기타 : https://docs.python.org/3.7/library/functions.html#open # 상대 경로('../', './'), 절대 경로 확인('C:\...') # 파일 읽기 # 예제1 print("#==== 파일 읽기 ====") print("#=== 파일 읽기 1 ===") f = open('./resource/review.txt', 'r') contents = f.read() print(contents) # print(dir(f)) # 반드시 close 리소스 반환 f.close() print() # 예제2 print("#=== 파일 읽기 2 - with ===") # with 는 close()를 사용 안해도 된다. with open('./resource/review.txt', 'r') as f: c = f.read() print(iter(c)) print(list(c)) print(c) print() # read : 전체 내용 읽기, read(10) : 10글자 읽기 # 예제3 print("#=== 파일 읽기 3 - strip() ===") with open('./resource/review.txt', 'r') as f: for c in f: # print(c) print(c.strip()) print() # 예제4 print("#=== 파일 읽기 4 - 커서위치 ===") with open('./resource/review.txt', 'r') as f: contents = f.read() print('>', contents) # 파일을 읽은 뒤 커서를 맨 끝에 위치시킨다. contents = f.read() print('>', contents) # 내용 없음 f.seek(0, 0) contents = f.read() print('>', contents) # readline : 한 줄씩 읽기, readline(문자수) : 문자수 읽기 print() # 예제5 print("#=== 파일 읽기 5 - readline() 한줄씩 ===") with open('./resource/review.txt', 'r') as f: # 한줄씩 읽어 온다. line = f.readline() while line: print(line, end='') line = f.readline() # readlines : 전체 읽은 후 라인 단위 리스트 저장 print() print() # 예제6 print("#=== 파일 읽기 6 - readlines() 리스트형태 ===") with open('./resource/review.txt', 'r') as f: contents = f.readlines() print(contents) print() # list 하나씩 빼오기 for c in contents: print(c, end='') print() print() # 예제7 print("#=== 파일 읽기 7 - append() 읽어서 추가 ===") with open('./resource/score.txt', 'r') as f: score = [] for line in f: score.append(int(line)) print(score) print('Average : {:6.3f}'.format(sum(score) / len(score))) # 파일 쓰기 print() print() print() print() print() print("#==== 파일 쓰기 ====") # 예제1 print("#=== 파일 쓰기 w ===") with open('./resource/test.txt', 'w') as f: f.write('niceman!') print( r""" with open('./resource/test.txt', 'w') as f: f.write('niceman!') """ ) print("#=== ./resource/test.txt 파일내용 ===") with open('./resource/test.txt', 'r') as f: c = f.read() print(c) print() print() # 예제2 print("#=== 파일 쓰기 a ===") with open('./resource/test.txt', 'a') as f: f.write('niceman!!') print( r""" with open('./resource/test.txt', 'a') as f: f.write('niceman!!') """ ) print("#=== ./resource/test.txt 파일내용 ===") with open('./resource/test.txt', 'r') as f: c = f.read() print(c) print() print() # 예제3 print("#=== 파일 쓰기 random w ===") from random import randint with open('./resource/score2.txt', 'w') as f: # range(6) -> 0~5 for cnt in range(6): # randint(50, 100) -> 50 ~ 100 중 랜덤 한 숫자 f.write(str(randint(50, 100))) f.write('\n') print( r""" from random import randint with open('./resource/score2.txt', 'w') as f: # range(6) -> 0~5 for cnt in range(6): # randint(50, 100) -> 50 ~ 100 중 랜덤 한 숫자 f.write(str(randint(50, 100))) f.write('\n') """ ) print("#=== ./resource/score2.txt 파일내용 ===") with open('./resource/score2.txt', 'r') as f: c = f.read() print(c) print() print() # 예제4 # writelines : 리스트 -> 파일로 저장 print("#=== 파일 쓰기 writelines 리스트 -> 파일로 저장 ===") with open('./resource/test2.txt', 'w') as f: list = ['Kim\n', 'Park\n', 'Lee\n'] f.writelines(list) print( r""" with open('./resource/test2.txt', 'w') as f: list = ['Kim\n', 'Park\n', 'Lee\n'] f.writelines(list) """ ) print("#=== ./resource/test2.txt 파일내용 ===") with open('./resource/test2.txt', 'r') as f: c = f.read() print(c) print() print() # 예제5 print("#=== 파일 쓰기 print() 를 파일에 씀 ===") with open('./resource/test3.txt', 'w') as f: print('Test Contents!', file=f) print('Test Contents!!', file=f) print( r""" with open('./resource/test3.txt', 'w') as f: print('Test Contents!', file=f) print('Test Contents!!', file=f) """ ) print("#=== ./resource/test3.txt 파일내용 ===") with open('./resource/test3.txt', 'r') as f: c = f.read() print(c) print() ==== 실행 콘솔 ==== #==== 파일 읽기 ==== #=== 파일 읽기 1 === The film, projected in the form of animation, imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues, which eventually paves the path for gaining a fresh perspective on an age-old problem. The story also happens to centre around two parallel characters, Shundi King and Hundi King, who are twins, but they constantly fight over unresolved issues planted in their minds by external forces from within their very own units. #=== 파일 읽기 2 - with === ['T', 'h', 'e', ' ', 'f', 'i', 'l', 'm', ',', ' ', 'p', 'r', 'o', 'j', 'e', 'c', 't', 'e', 'd', ' ', 'i', 'n', ' ', 't', 'h', 'e', ' ', 'f', 'o', 'r', 'm', ' ', 'o', 'f', ' ', 'a', 'n', 'i', 'm', 'a', 't', 'i', 'o', 'n', ',', '\n', 'i', 'm', 'p', 'a', 'r', 't', 's', ' ', 't', 'h', 'e', ' ', 'l', 'e', 's', 's', 'o', 'n', ' ', 'o', 'f', ' ', 'h', 'o', 'w', ' ', 'w', 'a', 'r', 's', ' ', 'c', 'a', 'n', ' ', 'b', 'e', ' ', 'e', 'l', 'u', 'd', 'e', 'd', ' ', 't', 'h', 'r', 'o', 'u', 'g', 'h', ' ', 'r', 'e', 'a', 's', 'o', 'n', 'i', 'n', 'g', ' ', 'a', 'n', 'd', ' ', 'p', 'e', 'a', 'c', 'e', 'f', 'u', 'l', ' ', 'd', 'i', 'a', 'l', 'o', 'g', 'u', 'e', 's', ',', '\n', 'w', 'h', 'i', 'c', 'h', ' ', 'e', 'v', 'e', 'n', 't', 'u', 'a', 'l', 'l', 'y', ' ', 'p', 'a', 'v', 'e', 's', ' ', 't', 'h', 'e', ' ', 'p', 'a', 't', 'h', ' ', 'f', 'o', 'r', ' ', 'g', 'a', 'i', 'n', 'i', 'n', 'g', ' ', 'a', ' ', 'f', 'r', 'e', 's', 'h', ' ', 'p', 'e', 'r', 's', 'p', 'e', 'c', 't', 'i', 'v', 'e', ' ', 'o', 'n', ' ', 'a', 'n', ' ', 'a', 'g', 'e', '-', 'o', 'l', 'd', ' ', 'p', 'r', 'o', 'b', 'l', 'e', 'm', '.', '\n', 'T', 'h', 'e', ' ', 's', 't', 'o', 'r', 'y', ' ', 'a', 'l', 's', 'o', ' ', 'h', 'a', 'p', 'p', 'e', 'n', 's', ' ', 't', 'o', ' ', 'c', 'e', 'n', 't', 'r', 'e', ' ', 'a', 'r', 'o', 'u', 'n', 'd', ' ', 't', 'w', 'o', ' ', 'p', 'a', 'r', 'a', 'l', 'l', 'e', 'l', ' ', 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's', ',', ' ', 'S', 'h', 'u', 'n', 'd', 'i', ' ', 'K', 'i', 'n', 'g', ' ', 'a', 'n', 'd', ' ', 'H', 'u', 'n', 'd', 'i', ' ', 'K', 'i', 'n', 'g', ',', '\n', 'w', 'h', 'o', ' ', 'a', 'r', 'e', ' ', 't', 'w', 'i', 'n', 's', ',', ' ', 'b', 'u', 't', ' ', 't', 'h', 'e', 'y', ' ', 'c', 'o', 'n', 's', 't', 'a', 'n', 't', 'l', 'y', ' ', 'f', 'i', 'g', 'h', 't', ' ', 'o', 'v', 'e', 'r', ' ', 'u', 'n', 'r', 'e', 's', 'o', 'l', 'v', 'e', 'd', ' ', 'i', 's', 's', 'u', 'e', 's', ' ', 'p', 'l', 'a', 'n', 't', 'e', 'd', ' ', 'i', 'n', ' ', 't', 'h', 'e', 'i', 'r', ' ', 'm', 'i', 'n', 'd', 's', '\n', 'b', 'y', ' ', 'e', 'x', 't', 'e', 'r', 'n', 'a', 'l', ' ', 'f', 'o', 'r', 'c', 'e', 's', ' ', 'f', 'r', 'o', 'm', ' ', 'w', 'i', 't', 'h', 'i', 'n', ' ', 't', 'h', 'e', 'i', 'r', ' ', 'v', 'e', 'r', 'y', ' ', 'o', 'w', 'n', ' ', 'u', 'n', 'i', 't', 's', '.'] The film, projected in the form of animation, imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues, which eventually paves the path for gaining a fresh perspective on an age-old problem. The story also happens to centre around two parallel characters, Shundi King and Hundi King, who are twins, but they constantly fight over unresolved issues planted in their minds by external forces from within their very own units. #=== 파일 읽기 3 - strip() === The film, projected in the form of animation, imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues, which eventually paves the path for gaining a fresh perspective on an age-old problem. The story also happens to centre around two parallel characters, Shundi King and Hundi King, who are twins, but they constantly fight over unresolved issues planted in their minds by external forces from within their very own units. #=== 파일 읽기 4 - 커서위치 === > The film, projected in the form of animation, imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues, which eventually paves the path for gaining a fresh perspective on an age-old problem. The story also happens to centre around two parallel characters, Shundi King and Hundi King, who are twins, but they constantly fight over unresolved issues planted in their minds by external forces from within their very own units. > > The film, projected in the form of animation, imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues, which eventually paves the path for gaining a fresh perspective on an age-old problem. The story also happens to centre around two parallel characters, Shundi King and Hundi King, who are twins, but they constantly fight over unresolved issues planted in their minds by external forces from within their very own units. #=== 파일 읽기 5 - readline() 한줄씩 === The film, projected in the form of animation, imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues, which eventually paves the path for gaining a fresh perspective on an age-old problem. The story also happens to centre around two parallel characters, Shundi King and Hundi King, who are twins, but they constantly fight over unresolved issues planted in their minds by external forces from within their very own units. #=== 파일 읽기 6 - readlines() 리스트형태 === ['The film, projected in the form of animation,\n', 'imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues,\n', 'which eventually paves the path for gaining a fresh perspective on an age-old problem.\n', 'The story also happens to centre around two parallel characters, Shundi King and Hundi King,\n', 'who are twins, but they constantly fight over unresolved issues planted in their minds\n', 'by external forces from within their very own units.'] The film, projected in the form of animation, imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues, which eventually paves the path for gaining a fresh perspective on an age-old problem. The story also happens to centre around two parallel characters, Shundi King and Hundi King, who are twins, but they constantly fight over unresolved issues planted in their minds by external forces from within their very own units. #=== 파일 읽기 7 - append() 읽어서 추가 === [95, 78, 92, 89, 100, 66] Average : 86.667 #==== 파일 쓰기 ==== #=== 파일 쓰기 w === with open('./resource/test.txt', 'w') as f: f.write('niceman!') #=== ./resource/test.txt 파일내용 === niceman! #=== 파일 쓰기 a === with open('./resource/test.txt', 'a') as f: f.write('niceman!!') #=== ./resource/test.txt 파일내용 === niceman!niceman!! #=== 파일 쓰기 random w === from random import randint with open('./resource/score2.txt', 'w') as f: # range(6) -> 0~5 for cnt in range(6): # randint(50, 100) -> 50 ~ 100 중 랜덤 한 숫자 f.write(str(randint(50, 100))) f.write('\n') #=== ./resource/score2.txt 파일내용 === 83 68 50 73 60 71 #=== 파일 쓰기 writelines 리스트 -> 파일로 저장 === with open('./resource/test2.txt', 'w') as f: list = ['Kim\n', 'Park\n', 'Lee\n'] f.writelines(list) #=== ./resource/test2.txt 파일내용 === Kim Park Lee #=== 파일 쓰기 print() 를 파일에 씀 === with open('./resource/test3.txt', 'w') as f: print('Test Contents!', file=f) print('Test Contents!!', file=f) #=== ./resource/test3.txt 파일내용 === Test Contents! Test Contents!! ===== Tip ===== {{tag>도봉산핵주먹 python 파일읽기 파일쓰기}}