[요약] 파이썬(Python) - 파일 읽기 / 쓰기
파이썬 코드로
파일을 읽을 수 있다
파일을 쓸 수 있다.
라인단위(한줄씩)로 읽고 쓸 수 있다.
파일을 list 형식으로 읽을 수 있다.
파일을 list 형식으로 쓸 수 있다.
print 함수를 파일로 리다이렉션 할 수 있다.
# 파이썬(Python) 파일 읽기(Read)/쓰기(Write)의 이해 # 파일 읽기 쓰기 모드 # 읽기 : r, 쓰기(기존파일 삭제됨) : w, 추가모드(파일생성 또는 추가) : a # 파일읽기 # 예1) print('예1) ---------------------------') f = open('./resource/review.txt') content = f.read() # 파일 내용을 읽어서 content에 저장 print(content) # result>>>> # This file is example text file. # review.txt print(dir(f)) # 파일핸들 f에 대한 출력 # result>>>> # ['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', ....... ] # 반드시 close를 이용해 파일핸들 리소스 반환 f.close() print('예2) ---------------------------') # 예2) - open의 다른 예시 (with를 사용하면 자동으로 close 처리됨) with open('./resource/review.txt') as f: c = f.read() print(c) print(list(c)) # 리스트형식으로 출력 : 각 문자단위로 ... print(iter(c)) print('예3) ---------------------------') # 예3) 캐리지리턴(CR)을 인식하여 한 줄씩 읽기 with open('./resource/review.txt', 'r') as f: for c in f: print(c) print('예4) ---------------------------') # 예4) EOF의 인식 with open('./resource/review.txt', 'r') as f: content = f.read() print('>', content) content = f.read() # 앞에서 이미 EOF에 도달했기 때문에 읽혀진 데이터는 없음 print('>', content) print('예5) ---------------------------') # 예5) 한줄씩 읽기 함수 사용 "readline()" with open('./resource/review.txt', 'r') as f: line = f.readline() print(line) while line: # line이 null이 아닐때까지 라인 읽기 효과 print(line, end='###') line = f.readline() print('예6) ---------------------------') # 예6) 한줄씩 읽기 함수 사용 "readlines()", 리스트형태로 결과를 가져옴 with open('./resource/review.txt', 'r') as f: contents = f.readlines() print(contents) # ['This file is example text file.\n', 'review.txt\n'] for c in contents: print(c, end='>>>>') # result >>>> # This file is example text file. # >>>>review.txt # >>>> print('예7) ---------------------------') # 예7) score = [] with open('./resource/score.txt', 'r') as f: for line in f: score.append(int(line)) print(score) print('average : {:6.3}'.format(sum(score)/len(score))) ##################################################################### #### 파일 쓰기 ##### ##################################################################### # 예1) 문자열 쓰기 with open('./resource/filewrite1.txt', 'w') as f: f.write('Niceman') # 예2) 한줄 쓰기 with open('./resource/filewrite1.txt', 'w') as f: f.write('Goodman!\n') # 예3) 랜덤값 반복 쓰기 from random import randint # random 모듈에서 randint 함수를 import with open('./resource/filewrite2.txt', 'w') as f: for cnt in range(5): f.write(str(randint(0, 50))) f.write('\n') # 예4) writelines : 리스트 -> 파일로 저장 with open('./resource/filewrite3.txt', 'w') as f: list = ['Kim\n', 'Lee\n', 'Choi\n', 'Park\n'] f.writelines(list) # 예5) print를 파일로 리다이렉션 쓰기 with open('./resource/filewrite4.txt', 'w') as f: print('Test contents1', file=f) print('Test contents2', file=f)
'프로그래밍 > Python' 카테고리의 다른 글
[요약] 파이썬(Python) - 엑셀(Excel)/CSV 파일 읽기 쓰기 (0) | 2020.12.06 |
---|---|
[요약] 파이썬(Python) - 예외처리(Exception) (0) | 2020.12.02 |
[요약] 파이썬(Python) - 모듈과 패키지 개념 이해 (0) | 2020.11.29 |
[요약] 파이썬(Python) - 클래스(Class) 사용법 (0) | 2020.11.23 |
[요약] 파이썬(Python) - 함수와 람다 사용법 (0) | 2020.11.13 |