-
Python: 파일 입출력(이진 파일, shutil, os, os.path) 예외처리 참고Python 2021. 3. 27. 12:32
Python: 파일 입출력 (읽기, 쓰기, 복사, 암호화 및 복호화) 참고
1. 파일읽기 readline을 이용한 파일 읽기(한줄씩) inFp = open("C:/data/practice.txt", 'r', encoding='utf-8') inStr = inFp.readline() print(inStr) inStr = inFp.readline() print(inStr) inStr = inFp.read..
seungjuitmemo.tistory.com
< 이진 파일 복사하기 >
# 이진 파일 복사하기 infp = open("C:/data/test.txt", 'rb') # rb는 read binary outfp = open("C:/data/test_tmp.txt", 'wb') # wb는 write binary while True: inStr = infp.read(1) if not inStr: break outfp.write(inStr) infp.close() outfp.close()
< shutil 과 os >
2.1. test.tx파일을 test_copy.txt로 복사하기
# shutil을 이용해서 파일 복사하기 - import shutil shutil.copy("C:/data/test.txt", "C:/data/test_copy.txt")
2.2. data 디렉토리를 data2디렉토리로 복사하기
import shutil shutil.copytree("C:/data", "C:/data2")
2.3. os 모듈로 디렉토리 만들고 shutil 모듈로 디렉토리 지우기
import os import shutil # 디렉토리 만들기 os.mkdir('C:/data3/') os.mkdir('C:/data3/data3_in_dir') # 디렉토리 지우기 shutil.rmtree('C:/data3')
2.4. 디렉토리 내부 모든 파일 경로 출력하기
# 디렉토리 내부의 모든 파일 출력하기(디렉토리 내부 디렉토리 안의 파일도 포함) import os for dirName, subDirList, fnames in os.walk('C:/data'): for fname in fnames: fullpath = os.path.join(dirName, fname) print(fullpath)
2.5. 파일 삭제하기
# 파일 삭제하기 import os try: os.remove('C:/data/test.txt') except: print("파일이 없습니다.")
2.6. 파일 사이즈 구하기
# 파일 크기 확인하기(바이트 단위) import os.path size = os.path.getsize('C:/data/test_copy.txt') print(size)
< 예외 처리 사용하기 >
3.1. try catch 사용하기
myStr = '파이썬은 재미 있어요. 파이썬만 매일매일 공부하고 싶어요' strPosList = [] index = 0 while True: try: index = myStr.index("파이썬", index) strPosList.append(index) index += 1 except: break print('문자열 위치: ',strPosList)
2.2. 로그 기록하는 파일 만들기
country = ['한국', '일본', '중국', '태국', '러시아', '베트남'] con = '' ans = None while True: try: # 실행하기 con = input("나라를 입력하세요 : ") ans = country.index(con) except ValueError as e: # valueerror 발생시 변수 e에 로그 저장하기 print(e, "국가는 리스트에 존재하지 않습니다.", "로그기록") outFp = open('C:/data/log.txt', 'a') outFp.write(con + '\n') outFp.close() except KeyboardInterrupt: # crtl + c 입력시 종료 break else: # 에러가 발생하지 않으면 ans출력 print(ans)
반응형'Python' 카테고리의 다른 글
Python: Window programming Tkinter 라이브러리 정리 1 (0) 2021.04.09 Python: 클래스, 멀티스레딩, 멀티프로세싱(Class, Multi threading, Multi Processing) 참고 (0) 2021.04.03 Python: 파일 입출력 (읽기, 쓰기, 복사, 암호화 및 복호화) 참고 (0) 2021.03.19 Python: 리스트, 문자열, 제어문, 튜플, 딕셔너리 참고 (0) 2021.03.12 Python: 견고한 객체지향 프로그래밍 SOLID 설계원칙 공부하기! (0) 2020.08.16