Python에 디렉토리가 있는지 어떻게 확인하나요?
디렉토리가 존재하는지 확인하려면 어떻게 해야 합니까?
디렉토리에만 사용:
>>> 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
현재 존재하는 디렉토리의 이름을 전달할 경우.됩니다.False
.
네, 를 사용합니다.
2개의 내장 기능으로 확인할 수 있습니다.
os.path.isdir("directory")
지정된 디렉토리를 사용할 수 있는 boolean true가 됩니다.
os.path.exists("directoryorfile")
지정된 디렉토리 또는 파일을 사용할 수 있는 경우 boolead true가 됩니다.
경로가 디렉토리인지 확인하려면
os.path.isdir("directorypath")
경로가 디렉토리인 경우 boolean true가 됩니다.
다음 코드는 코드의 참조된 디렉토리가 존재하는지 여부를 확인합니다. 이 디렉토리가 작업영역에 존재하지 않을 경우 디렉토리가 생성됩니다.
import os
if not os.path.isdir("directory_name"):
os.mkdir("directory_name")
예:
In [3]: os.path.exists('/d/temp')
Out[3]: True
아마 던질거야os.path.isdir(...)
★★★★★★★★★★★★★★★★★★.
「 」를하기 .os.stat
2 버전(복수 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
디렉토리가 없는 경우에도 디렉토리를 작성할 수 있습니다.
소스, 아직 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
또한 권한 부족, 전체 디스크 등 다른 요인에 의한 디렉토리 생성 실패를 무시하기 때문에 오류가 발생하지 않습니다.
은 1개의 이더넷을 입니다.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.
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'
두 가지
- 디렉토리가 존재하는지 확인하시겠습니까?
- 그렇지 않은 경우 디렉토리를 만듭니다(선택사항).
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 모듈을 Import합니다.
코드를 실행하기 전에 os.path 모듈을 Import합니다.
import os.path
from os import path
스텝 2: 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()
Python 3.4의 경우 pathlibPath.exists()
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(): 경로가 File이면 True를 반환합니다.
- os.path.isdir(): 경로가 Directory일 경우 True를 반환합니다.
- pathlib.Path.exists(): 경로 또는 디렉토리가 존재하는 경우 True를 반환합니다.(Python 3.4 이상 버전)
언급URL : https://stackoverflow.com/questions/8933237/how-do-i-check-if-directory-exists-in-python
'it-source' 카테고리의 다른 글
한 번에 모든 MySQL 데이터베이스 내보내기 및 가져오기 (0) | 2023.02.02 |
---|---|
VueJ별 입력값 설정 및 가치내용 혼합 (0) | 2023.02.02 |
제한 글로벌 없음 (0) | 2023.02.02 |
PHP 클래스 컨스트럭터가 부모 컨스트럭터를 호출하려면 어떻게 해야 합니까? (0) | 2023.02.02 |
JavaScript에서 "function*"란 무엇입니까? (0) | 2023.02.02 |