Program Tip

Python에 디렉토리가 있는지 확인하는 방법

programtip 2020. 9. 27. 13:48
반응형

Python에 디렉토리가 있는지 확인하는 방법


osPython 모듈에서 다음과 같이 디렉토리가 있는지 확인하는 방법이 있습니까?

>>> os.direxists(os.path.join(os.getcwd()), 'new_folder')) # in pseudocode
True/False

을 찾고 os.path.isdir있거나 os.path.exists파일인지 디렉토리인지 상관하지 않습니다.

예:

import os
print(os.path.isdir("/home/el"))
print(os.path.exists("/home/el/myfile.txt"))

너무 가까이! 현재 존재하는 디렉토리의 이름을 전달하면 os.path.isdir반환 True됩니다. 존재하지 않거나 디렉토리가 아니면를 반환합니다 False.


Python 3.4는 파일 시스템 경로를 처리하는 객체 지향 접근 방식을 제공하는 표준 라이브러리에 모듈도입 했습니다pathlib .

In [1]: from pathlib import Path

In [2]: p = Path('/usr')

In [3]: p.exists()
Out[3]: True

In [4]: p.is_dir()
Out[4]: True

In [5]: q = p / 'bin' / 'vim'

In [6]: q.exists()
Out[6]: True

In [7]: q.is_dir()
Out[7]: False

Pathlib는 PyPi 의 pathlib2 모듈을 통해 Python 2.7에서도 사용할 수 있습니다 .


예, os.path.exists().


2 개의 내장 기능으로 확인할 수 있습니다

os.path.isdir("directory")

지정된 디렉토리를 사용할 수있는 부울 true를 제공합니다.

os.path.exists("directoryorfile")

지정된 디렉토리 또는 파일을 사용할 수 있으면 boolead가 true가됩니다.

경로가 디렉토리인지 확인하려면

os.path.isdir("directorypath")

경로가 디렉토리이면 부울 true를 제공합니다.


os.path.isdir (path) 사용


에서와 같이 :

In [3]: os.path.exists('/d/temp')
Out[3]: True

os.path.isdir(...)확실히 하기 위해 a 던질 것 입니다.


os.stat버전 을 제공하기 위해 (python 2) :

import os, stat, errno
def CheckIsDir(directory):
  try:
    return stat.S_ISDIR(os.stat(directory).st_mode)
  except OSError, e:
    if e.errno == errno.ENOENT:
      return False
    raise

os는 다음과 같은 많은 기능을 제공합니다.

import os
os.path.isdir(dir_in) #True/False: check if this is a directory
os.listdir(dir_in)    #gets you a list of all files and directories under dir_in

입력 경로가 유효하지 않은 경우 listdir은 예외를 발생시킵니다.


#You can also check it get help for you

if not os.path.isdir('mydir'):
    print('new directry has been created')
    os.system('mkdir mydir')

편리한 Unipath모듈이 있습니다.

>>> from unipath import Path 
>>>  
>>> Path('/var/log').exists()
True
>>> Path('/var/log').isdir()
True

필요한 기타 관련 항목 :

>>> Path('/var/log/system.log').parent
Path('/var/log')
>>> Path('/var/log/system.log').ancestor(2)
Path('/var')
>>> Path('/var/log/system.log').listdir()
[Path('/var/foo'), Path('/var/bar')]
>>> (Path('/var/log') + '/system.log').isfile()
True

pip를 사용하여 설치할 수 있습니다.

$ pip3 install unipath

It's similar to the built-in pathlib. The difference is that it treats every path as a string (Path is a subclass of the str), so if some function expects a string, you can easily pass it a Path object without a need to convert it to a string.

For example, this works great with Django and settings.py:

# settings.py
BASE_DIR = Path(__file__).ancestor(2)
STATIC_ROOT = BASE_DIR + '/tmp/static'

참고URL : https://stackoverflow.com/questions/8933237/how-to-find-if-directory-exists-in-python

반응형