본문 바로가기

파이썬(PYTHON)/개념정리
[파이썬(Python)] 디렉토리, 예외 처리

not

list = [1,2,3,4,5]

print( 7 not in list)
print( 7 in list)
print( 2 in list)
print( 2 not in list)


==========================================================================
==============

 

디렉토리 생성

#디렉토리 : 폴더

- os 모듈을 이용함. import os
- os.mkdir(“디렉토리명”) #C:\\abcd 가능함.

from os import *
mkdir("d:/sample")


==========================================================================
==============

디렉토리 삭제

- os 모듈을 이용함. import os
- os.rmdir(“디렉토리명”) #C:\\abcd 가능함

from os import *
rmdir("d:/sample")


==========================================================================
==============

os 관련 함수

'''
#os 관련 함수

- os.listdir(path) : path 경로에 있는 모든 파일 및 디렉토리를 보여줌
- os.path.isdir(path) : path가 디렉토리면 true, 그렇지 않으면 false
- os.path.isfile(path) : path가 파일이면 true, 그렇지 않으면 false

괄호 안의 path 는 디렉토리가 들어갈 수도 있고, 파일이 들어갈 수도 있음!!!!
'''

from os import *

print("\n=======================================")

for i in listdir("d:/python") :
    print(i, end=" / ") 

print("\n=======================================\n")

print( path.isdir("d:/python") )
print( path.isdir("d:/sample") )

print("\n=======================================\n")

print( path.isfile("d:/python") )
print( path.isfile("d:/sample") )

print("\n=======================================\n")


==========================================================================
==============

예외

- 예외(Exception) : 프로그램의 실행 중에 정상적이지 않은 흐름(이벤트)를 말함.
    ~의도치 않게 발생, 비정상 종료
    ~ex) ★indexError, ZeroDivisionError, FileNotFoundError ...
    
- 일반적으로 처리 불가능한 상황이 오면 예외를 발생함.

a = [1,2,3,4,5]

print(a[0])
print(a[1])
print(a[6])

=============================

a = 5
b = 0

print(a/b)

============================

f = open("d:/test.txt", 'r')

f.close()


==========================================================================
==============

예외 처리 - try...except... / try...except...finally

'''
#★★★예외 처리

- 파이썬이 예외를 발생하면, 예외에 맞는 처리를 해줘야 함. (예외에 맞는 처리를 안하면 종료됨.)

- 예외 처리는 try : except : 문을 사용함.
    ~try :
      예외가 발생할 수 있는 코드
      
    ~except ExceptionName1 :
     예외처리 코드
     
    ~except ExceptionName2 : 
     예외처리 코드
     
    ~else :
     예외가 발생하지 않으면 실행하는 코드

- try... except...finally : finally는 예외가 발생하든 안 하든 반드시 실행시키는 부분
'''

a = [1,2,3,4,5]

print("===============================\n\n\n\n\n")

try :
    print(a[6])

except IndexError :
    print("잘못된 범위값을 넣으셨습니다.\n")

print("===============================\n\n\n\n\n")

try :
    print(a[6])

except Exception : #Exception : 모든 예외를 통틀어서 칭함 
    print("잘못된 범위값을 넣으셨습니다.\n")
    
print("===============================\n\n\n\n\n")

try :
    print(a[6])

except Exception as error :  #error은 변수명! 자유롭게 설정 가능. 예외 설명을 담음
    print("잘못된 범위값을 넣으셨습니다.")
    print(error)

print("\n===============================\n\n\n\n")

f = open("d:/test.txt", 'w')
try :
    f.write("곧 집에 갈 시간입니다.")

except Exception as error : 
    print("파일을 찾을 수 없습니다.")
    print(error)

finally :
    f.close()

print("\n===============================\n\n\n\n")


==========================================================================
==============

예외 강제 발생

'''
# 예외 강제 발생

- raise 문을 사용하여 예외를 발생시킬 수 있음

- raise Exception_name(예외 설명)

'''

def appleSum(num1, num2) :
    if ( num1 < 0 or num2 < 0) :
        raise Exception("음수가 들어왔습니다.")

    return num1 + num2


try :
    total = appleSum(-1, 5)

except Exception as e :
    print(e)