sourcecode

파이썬에 디렉터리가 있는지 확인하려면 어떻게 해야 합니까?

codebag 2023. 5. 13. 09:40
반응형

파이썬에 디렉터리가 있는지 확인하려면 어떻게 해야 합니까?

파이썬에 디렉터리가 있는지 확인하려면 어떻게 해야 합니까?

디렉터리에만 사용:

>>> import os
>>> os.path.isdir('new_folder')
True

파일 및 디렉터리 모두에 사용:

>>> import os
>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
False

또는 다음을 사용할 수 있습니다.

 >>> from pathlib import Path
 >>> Path('new_folder').is_dir()
 True
 >>> (Path.cwd() / 'new_folder' / 'file.txt').exists()
 False

Python 3.4는 표준 라이브러리에 모듈을 도입하여 파일 시스템 경로를 처리하는 객체 지향 접근 방식을 제공합니다.is_dir()그리고.exists()Path개체를 사용하여 다음 질문에 답할 수 있습니다.

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
Out[6]: PosixPath('/usr/bin/vim') 

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

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

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

아깝다! os.path.isdir아온다를 합니다.True현재 존재하는 디렉토리의 이름을 전달하는 경우.에는 지않디렉가아리닌토경해우반디다환가됩니리렉토당존재거하나다▁if,반니▁returns환을 반환합니다.False.

예, 사용합니다.

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

os.path.isdir("directory")

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

os.path.exists("directoryorfile")

지정된 디렉터리 또는 파일을 사용할 수 있는 경우 boolead true가 됩니다.

경로가 디렉터리인지 확인합니다.

os.path.isdir("directorypath")

경로가 디렉토리인 경우 boolean true를 제공합니다.

예 os.path.isdir(경로)를 사용합니다.

다음 코드는 코드의 참조된 디렉터리가 존재하는지 여부를 확인합니다. 이 디렉터리가 작업영역에 존재하지 않으면 디렉터리가 생성됩니다.

import os

if not os.path.isdir("directory_name"):
    os.mkdir("directory_name")

디렉토리가 없는 경우 디렉토리를 작성할 수도 있습니다.

출처, 아직 SO에 있다면요.

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

Python » 3.5에서는 다음을 사용합니다.

from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)

이전 버전의 Python의 경우 각각 작은 결함이 있는 좋은 품질의 두 가지 답변을 볼 수 있습니다.

를 사용하여 작성을 고려합니다.

import os
if not os.path.exists(directory):
    os.makedirs(directory)

코멘트 등에서 언급한 바와 같이, 경쟁 조건이 있습니다. 디렉토리가 다음과 같은 사이에 생성되는 경우.os.path.exists 리고그고.os.makedirs 출호,os.makedirs됩니다.OSError를 잡는 것, 담를잡는것도게하요불.OSError사용 권한 부족, 전체 디스크 등의 다른 요인으로 인해 디렉터리를 만들지 못한 경우를 무시하기 때문에 계속 진행하는 것은 완벽하지 않습니다.

한 가지 방법은 다음과 같습니다.OSError내장된 오류 코드를 확인합니다(Python의 OSError에서 정보를 얻는 교차 플랫폼 방법이 있습니까 참조).

import os, errno

try:
    os.makedirs(directory)
except OSError as e:
    if e.errno != errno.EEXIST:
        raise

아니면, 두 번째가 있을 수도 있습니다.os.path.exists그러나 다른 사용자가 첫 번째 검사 후에 디렉터리를 만든 다음 두 번째 검사 전에 디렉터리를 제거했다고 가정하면, 우리는 여전히 속을 수 있습니다.

응용 프로그램에 따라 동시 작업의 위험이 파일 권한과 같은 다른 요인에 의해 발생하는 위험보다 많거나 적을 수 있습니다.개발자는 구현을 선택하기 전에 개발 중인 특정 애플리케이션과 해당 애플리케이션의 예상 환경에 대해 더 자세히 알아야 합니다.

현대 버전의 Python은 (3.3+에서) 노출을 통해 이 코드를 상당히 개선했습니다.

try:
    os.makedirs("path/to/directory")
except FileExistsError:
    # directory already exists
    pass

...키워드 인수 호출(3.2+)을 허용합니다.

os.makedirs("path/to/directory", exist_ok=True)  # succeeds even if directory exists.

다음과 같이:

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

아마도 던져넣을 것입니다.os.path.isdir(...)확실히

단지 그것을 제공하기 위해.os.stat버전(버전 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')

편리한 모듈이 있습니다.

>>> 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

기본 제공되는 기능과 유사합니다.pathlib차이점은 모든 경로를 문자열로 처리한다는 것입니다.Path의 하위 클래스입니다.str), 그래서 만약 어떤 함수가 문자열을 기대한다면, 당신은 그것을 쉽게 전달할 수 있습니다.Path개체를 문자열로 변환할 필요가 없습니다.

예를 들어, 이것은 장고와 잘 작동합니다.settings.py:

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

두가지

  1. 디렉토리가 존재하는지 확인하시겠습니까?
  2. 그렇지 않은 경우 디렉토리를 작성합니다(선택사항).
import os
dirpath = "<dirpath>" # Replace the "<dirpath>" with actual directory path.

if os.path.exists(dirpath):
   print("Directory exist")
else: #this is optional if you want to create a directory if doesn't exist.
   os.mkdir(dirpath):
   print("Directory created")

1단계: OS.path 모듈 가져오기
코드를 실행하기 전에 os.path 모듈을 가져옵니다.

import os.path
from os import path

2단계: Use path.exists() 함수
path.exists() 메서드는 파일의 존재 여부를 확인하는 데 사용됩니다.

path.exists("your_file.txt")

3단계: os.path.isfile() 사용
isfile 명령을 사용하여 지정된 입력이 파일인지 여부를 확인할 수 있습니다.

path.isfile('your_file.txt')

4단계: os.path.isdir() 사용
os.path.dir() 함수를 사용하여 지정된 입력이 디렉터리인지 여부를 확인할 수 있습니다.

path.isdir('myDirectory')

여기 완전한 코드가 있습니다.

    import os.path
    from os import path
    
    def main():
    
       print ("File exists:"+str(path.exists('your_file.txt')))
       print ("Directory exists:" + str(path.exists('myDirectory')))
       print("Item is a file: " + str(path.isfile("your_file.txt")))
       print("Item is a directory: " + str(path.isdir("myDirectory")))
    
    if __name__== "__main__":
       main()

PathlibPath.exists() Python 3.4의 경우

Pathlib Module은 파일 시스템 경로를 처리하기 위해 Python 3.4 이상 버전에 포함되어 있습니다.Python은 객체 지향 기술을 사용하여 폴더가 존재하는지 확인합니다.

import pathlib
file = pathlib.Path("your_file.txt")
if file.exists ():
    print ("File exist")
else:
    print ("File not exist")
  • os.path.exists() – 경로 또는 디렉터리가 있는 경우 True를 반환합니다.
  • os.path.isfile() – 경로가 파일인 경우 True를 반환합니다.
  • os.path.isdir() – 경로가 디렉터리인 경우 True를 반환합니다.
  • 통속적인Path.exists() – 경로 또는 디렉터리가 있으면 True를 반환합니다.(Python 3.4 이상 버전)

기사 참조 Python에 디렉터리가 있는지 확인하려면 어떻게 해야 합니까?

언급URL : https://stackoverflow.com/questions/8933237/how-do-i-check-if-a-directory-exists-in-python

반응형