파이썬에 파일이 있는지 확인하는 방법
- 
          
            파일 존재를 확인하는 try...except(> Python 2.x)
- 
          
            파일이 존재하는지 확인하기위한 os.path.isfile()(> = Python 2.x)
- 
          
            pathlib.Path.is_file()파일이 존재하는지 확인 (> = Python 3.4)
 
이 튜토리얼에서는 파일이 파이썬에 존재하는지 확인하는 세 가지 솔루션을 소개합니다.
- 파일 존재 여부를 확인하는 try...except블록 (> = Python 2.x)
- 파일 존재 여부를 확인하는 os.path.isfile함수 (> = Python 2.x)
- pathlib.Path.is_file()파일 존재 여부 확인 (> = Python 3.4)
파일 존재를 확인하는 try...except (> Python 2.x)
우리는 파일을 열려고 시도하여 IOError (Python 2.x) 또는 FileNotFoundError (Python 3.x)의 발생 여부에 따라 파일이 존재하는지 여부를 확인할 수 있습니다.
def checkFileExistance(filePath):
    try:
        with open(filePath, "r") as f:
            return True
    except FileNotFoundError as e:
        return False
    except IOError as e:
        return False
위의 예제 코드에서 예외 캐치 부분에 FileNotFoundError 와 IOError 를 모두 나열하여 Python 2/3과 호환되도록 만들었습니다.
파일이 존재하는지 확인하기위한 os.path.isfile()(> = Python 2.x)
import os
fileName = "temp.txt"
os.path.isfile(fileName)
fileName 파일이 존재하는지 확인합니다.
일부 개발자들은 os.path.exists()를 사용하여 파일이 존재하는지 확인하는 것을 선호합니다. 그러나 객체가 파일인지 디렉토리인지 구분할 수 없었습니다.
import os
fileName = "temp.txt"
print(os.path.exists(fileName))
fileName = r"C:\Test"
print(os.path.exists(fileName))
따라서 ** file **이 있는지 확인하려면 os.path.isfile 만 사용하십시오.
pathlib.Path.is_file()파일이 존재하는지 확인 (> = Python 3.4)
Python 3.4부터는 pathlib 모듈에 객체 지향 메소드를 도입하여 파일이 존재하는지 확인합니다.
from pathlib import Path
fileName = "temp.txt"
fileObj = Path(fileName)
print(fileObj.is_file())
마찬가지로 디렉토리 또는 파일/디렉토리가 존재하는지 확인하는 is_dir()및 exists()메소드도 있습니다.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook