try
문을 사용하지 않고 파일이 존재하는지 여부를 어떻게 알 수 있습니까?
검사하는 이유가 if file_exists: open_it()
과 같은 것을 할 수 있다면, 그것을 열려고 시도 할 때 try
을 사용하는 것이 더 안전합니다. 확인한 다음 열면 삭제되거나 이동 된 파일 또는 확인한 시점과 열려고하는 시점 사이의 위험이 있습니다.
파일을 바로 열지 않으려면 os.path.isfile
를 사용할 수 있습니다.
Path가 기존 일반 파일 인 경우
True
을 반환합니다. 이것은 심볼릭 링크를 따르므로 islink () 와 isfile () 은 같은 경로에서 참일 수 있습니다.
import os.path
os.path.isfile(fname)
파일인지 확인해야합니다.
Python 3.4부터는 pathlib
모듈 이 객체 지향 접근법 (Python 2.7에서 pathlib2
로 백 포트 됨)을 제공합니다.
from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
# file exists
디렉토리를 확인하려면 다음을 수행하십시오.
if my_file.is_dir():
# directory exists
Path
개체가 파일인지 디렉터리인지에 관계없이 존재하는지 여부를 확인하려면 exists()
을 사용합니다.
if my_file.exists():
# path exists
try
블록에서 resolve(strict=True)
을 사용할 수도 있습니다.
try:
my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
# doesn't exist
else:
# exists
os.path.exists
기능이 있습니다.
import os.path
os.path.exists(file_path)
이것은 파일과 디렉토리 모두에 대해 True
을 반환하지만 대신
os.path.isfile(file_path)
특정 파일인지 테스트합니다. 그것은 심볼릭 링크를 따른다.
isfile()
, exists()
는 디렉토리에 대해 True
을 반환합니다.
따라서 일반 파일이나 디렉토리 만 원한다면 isfile()
또는 exists()
을 사용하십시오. 간단한 REPL 출력이 있습니다.
>>> print os.path.isfile("/etc/password.txt")
True
>>> print os.path.isfile("/etc")
False
>>> print os.path.isfile("/does/not/exist")
False
>>> print os.path.exists("/etc/password.txt")
True
>>> print os.path.exists("/etc")
True
>>> print os.path.exists("/does/not/exist")
False
import os.path
if os.path.isfile(filepath):
os.path.isfile()
와 os.access()
를 사용하십시오.
import os
import os.path
PATH='./file.txt'
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
print "File exists and is readable"
else:
print "Either the file is missing or not readable"
import os
os.path.exists(path) # Returns whether the path (directory or file) exists or not
os.path.isfile(path) # Returns whether the file exists or not
이것은 파일이 있는지를 확인하는 가장 간단한 방법입니다. 그냥 왜냐하면 당신이 체크했을 때 파일이 존재했기 때문에 보장 당신이 그것을 열 필요가있을 때 거기있을 것입니다.
import os
fname = "foo.txt"
if os.path.isfile(fname):
print("file does exist at this time")
else:
print("no such file exists at this time")
Python 3.4+ 는 객체 지향 경로 모듈을 가지고 있습니다 : pathlib . 이 새 모듈을 사용하면 파일이 다음과 같은지 여부를 확인할 수 있습니다.
import pathlib
p = pathlib.Path('path/to/file')
if p.is_file(): # or p.is_dir() to see if it is a directory
# do stuff
파일을 열 때 try/except
블록을 계속 사용할 수 있습니다 (일반적으로 그래야 함).
try:
with p.open() as f:
# do awesome stuff
except OSError:
print('Well darn.')
Pathlib 모듈에는 편리한 globbing, 파일 소유자 확인, 경로 결합 등이 포함되어 있습니다. 체크 아웃 할 가치가 있습니다. 구형 Python (버전 2.6 이상)을 사용하고 있다면 pip와 함께 pathlib를 설치할 수 있습니다.
# installs pathlib2 on older Python versions
# the original third-party module, pathlib, is no longer maintained.
pip install pathlib2
그런 다음 다음과 같이 가져옵니다.
# Older Python versions
import pathlib2 as pathlib
Try 문을 선호하십시오. 더 나은 스타일로 간주되어 경쟁 조건을 피합니다.
그것을 위해 내 말을 들지 마십시오. 이 이론에 대한 많은 지원이 있습니다. 한 쌍있다 :
Try 문을 사용하지 않고 Python을 사용하여 파일이 존재하는지 어떻게 확인합니까?
이제 Python 3.4부터 사용 가능하며 파일 이름으로 Path
객체를 가져와 인스턴스화하고 _is_file
_ 메소드를 확인하십시오 (정규 파일을 가리키는 심볼릭 링크의 경우 True를 반환 함).
_>>> from pathlib import Path
>>> Path('/').is_file()
False
>>> Path('/initrd.img').is_file()
True
>>> Path('/doesnotexist').is_file()
False
_
Python 2에 있으면 pypi에서 pathlib 모듈을 백 포트하거나 pathlib2
또는 _os.path
_ 모듈에서 isfile
을 확인할 수 있습니다.
_>>> import os
>>> os.path.isfile('/')
False
>>> os.path.isfile('/initrd.img')
True
>>> os.path.isfile('/doesnotexist')
False
_
위의 내용은 아마도 가장 실용적인 직접 답변이지만, 달성하려는 목표에 따라 경쟁 조건이 발생할 가능성이 있으며 기본 구현은 try
을 사용하지만 Python는 구현의 모든 곳에서 try
을 사용합니다.
Python은 어디에서나 try
을 사용하기 때문에이를 사용하는 구현을 피할 이유가 없습니다.
그러나이 답변의 나머지 부분은 이러한주의 사항을 고려하려고합니다.
Python 3.4부터 사용 가능하므로 Path
에서 새로운 pathlib
객체를 사용하십시오. _.exists
_는 디렉토리가 파일이 아니기 때문에 옳지 않습니다 (유닉스 의미에서 모든 것 는 파일 임).
_>>> from pathlib import Path
>>> root = Path('/')
>>> root.exists()
True
_
따라서 _is_file
_를 사용해야합니다.
_>>> root.is_file()
False
_
_is_file
_에 대한 도움말은 다음과 같습니다.
_is_file(self)
Whether this path is a regular file (also True for symlinks pointing
to regular files).
_
우리가 알고있는 파일을 가져 오십시오 :
_>>> import tempfile
>>> file = tempfile.NamedTemporaryFile()
>>> filepathobj = Path(file.name)
>>> filepathobj.is_file()
True
>>> filepathobj.exists()
True
_
기본적으로 NamedTemporaryFile
은 파일을 닫을 때 파일을 삭제합니다 (더 이상 참조가 없으면 자동으로 닫힙니다).
_>>> del file
>>> filepathobj.exists()
False
>>> filepathobj.is_file()
False
_
구현 으로 들어가면 _is_file
_에서 try
을 사용한다는 것을 알 수 있습니다.
_def is_file(self):
"""
Whether this path is a regular file (also True for symlinks pointing
to regular files).
"""
try:
return S_ISREG(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False
_
경쟁 조건을 피하기 때문에 try
을 좋아합니다. try
을 사용하면 파일을 읽으려고 시도하고 파일이있을 것으로 예상하고 그렇지 않은 경우 예외를 포착하여 대체 동작이 의미가있는 모든 것을 수행합니다.
파일을 읽기 전에 파일이 존재하는지 확인하고 파일을 삭제 한 후 여러 스레드 또는 프로세스를 사용 중이거나 다른 프로그램이 해당 파일에 대해 알고 파일을 삭제할 수있는 경우 경주 조건 존재 여부를 확인하는 경우 racing 이 있기 때문에 조건 (존재)이 바뀝니다.
경쟁 조건은 프로그램이 실패 할 수있는 매우 작은 창이 있으므로 디버깅하기가 매우 어렵습니다.
그러나 이것이 동기라면 try
컨텍스트 관리자를 사용하여 can 값을 suppress
문의 값을 얻을 수 있습니다.
suppress
파이썬 3.4는 suppress
컨텍스트 관리자 (이전에는 ignore
컨텍스트 관리자)를 제공합니다.이 컨텍스트는 의미 적으로 정확히 적은 수의 줄로 정확히 동일한 것을 수행하면서도 try
문을 피하도록 원래 요청하십시오.
_from contextlib import suppress
from pathlib import Path
_
용법:
_>>> with suppress(OSError), Path('doesnotexist').open() as f:
... for line in f:
... print(line)
...
>>>
>>> with suppress(OSError):
... Path('doesnotexist').unlink()
...
>>>
_
이전 파이썬의 경우, 자신 만의 suppress
을 굴릴 수 있지만 try
이 없으면보다 더 장황합니다. 나는 이것은 실제로 파이썬 에서 try
을 사용하지 않는 유일한 대답이라고 Python 3.4 컨텍스트 관리자를 대신 사용하기 때문에 :
_class suppress(object):
def __init__(self, *exceptions):
self.exceptions = exceptions
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is not None:
return issubclass(exc_type, self.exceptions)
_
시도해 보면 더 쉬울 것입니다.
_from contextlib import contextmanager
@contextmanager
def suppress(*exceptions):
try:
yield
except exceptions:
pass
_
파일
_import os
os.path.isfile(path)
_
docs 에서 :
os.path.isfile(path)
Path가 기존 일반 파일 인 경우 True를 반환합니다. 이것은 심볼릭 링크를 따르므로
islink()
과isfile()
은 모두 동일한 경로에 대해 사실 일 수 있습니다.
그러나이 함수의 source 를 살펴보면 실제로 try 문을 사용한다는 것을 알 수 있습니다.
_# This follows symbolic links, so both islink() and isdir() can be true # for the same path on systems that support symlinks def isfile(path): """Test whether a path is a regular file""" try: st = os.stat(path) except os.error: return False return stat.S_ISREG(st.st_mode)
_
_>>> OSError is os.error
True
_
모든 것은 주어진 경로를 사용하여 통계를 얻을 수 있는지 확인하고 OSError
을 포착 한 다음 예외가 발생하지 않은 경우 파일인지 확인하는 것입니다.
파일로 무언가를하려는 경우 경쟁 조건을 피하기 위해 시도를 제외하고 직접 시도해 보는 것이 좋습니다.
_try:
with open(path) as f:
f.read()
except OSError:
pass
_
os.access
유닉스와 Windows에서 사용할 수있는 것은 _os.access
_이지만 사용하려면 플래그를 전달해야하며 파일과 디렉토리를 구분하지 않습니다. 실제 호출하는 사용자가 상승 된 권한 환경에서 액세스 할 수 있는지 테스트하는 데 더 사용됩니다.
_import os
os.access(path, os.F_OK)
_
또한 isfile
과 동일한 경쟁 조건 문제가 있습니다. docs 에서 :
참고 : access ()를 사용하여 사용자에게 권한이 있는지 확인하십시오. 실제로 파일을 열기 전에 open ()을 사용하면 파일을 확인하고 열어서 파일을 조작하는 데 걸리는 짧은 시간 간격을 이용할 수 있으므로 보안 허점이 생깁니다. EAFP 기술을 사용하는 것이 좋습니다. 예를 들면 다음과 같습니다.
_if os.access("myfile", os.R_OK): with open("myfile") as fp: return fp.read() return "some default data"
_다음과 같이 작성하는 것이 좋습니다.
_try: fp = open("myfile") except IOError as e: if e.errno == errno.EACCES: return "some default data" # Not a permission error. raise else: with fp: return fp.read()
_
_os.access
_를 사용하지 마십시오. 위에서 설명한 상위 수준 개체 및 기능보다 사용자 오류 가능성이 더 낮은 하위 수준 기능입니다.
또 다른 답변은 _os.access
_에 대해 다음과 같이 말합니다.
개인적으로 필자는 기본 API ( "$ {PYTHON_SRC_DIR} /Modules/posixmodule.c"를 통해)를 호출하지만 가능한 사용자 오류에 대한 문을 열며 다른 변형만큼 Pythonic이 아니기 때문에 이것을 선호합니다. :
이 답변은 정당화없이 비 피톤의 오류가 발생하기 쉬운 방법을 선호한다고 말합니다. 사용자가 이해하지 않고 저수준 API를 사용하도록 권장하는 것 같습니다.
또한 무조건 True
을 반환하여 모든 예외 (KeyboardInterrupt
및 SystemExit
! 포함)를 자동으로 전달할 수있는 컨텍스트 관리자를 생성하므로 버그를 숨길 수 있습니다.
이것은 사용자가 열악한 관행을 채택하도록 장려하는 것 같습니다.
import os
#Your path here e.g. "C:\Program Files\text.txt"
#For access purposes: "C:\\Program Files\\text.txt"
if os.path.exists("C:\..."):
print "File found!"
else:
print "File not found!"
os
을 가져 오면 운영 체제에서 표준 작업을보다 쉽게 탐색하고 수행 할 수 있습니다.
참조 정보는 파이썬을 사용하여 파일이 존재하는지 확인하는 방법을 참조하십시오.
높은 수준의 작업이 필요한 경우 shutil
을 사용하십시오.
os.path.isfile()
, os.path.isdir()
및 os.path.exists()
을 사용하여 파일 및 폴더 테스트
"경로"가 유효한 경로라고 가정하면이 테이블은 파일 및 폴더에 대해 각 함수가 반환하는 내용을 보여줍니다.
또한 os.path.splitext()
을 사용하여 파일을 특정 유형의 파일인지 테스트 할 수 있습니다 (아직 모르는 경우).
>>> import os
>>> path = "path to a Word document"
>>> os.path.isfile(path)
True
>>> os.path.splitext(path)[1] == ".docx" # test if the extension is .docx
True
2016 년 가장 좋은 방법은 여전히 os.path.isfile
를 사용하는 것입니다.
>>> os.path.isfile('/path/to/some/file.txt')
또는 파이썬 3에서는 pathlib
을 사용할 수 있습니다 :
import pathlib
path = pathlib.Path('/path/to/some/file.txt')
if path.is_file():
...
Try/except와 isfile()
사이에 의미있는 기능 차이가있는 것처럼 보이지 않으므로 어느 것이 합리적인지 사용해야합니다.
파일을 읽으려는 경우 파일이 있으면이를 수행하십시오.
try:
f = open(filepath)
except IOError:
print 'Oh dear.'
그러나 파일이 존재하는 경우 파일의 이름을 바꿔서 열 필요가없는 경우에는
if os.path.isfile(filepath):
os.rename(filepath, filepath + '.old')
파일에 쓰기를 원한다면, 그것이 존재하지 않는다면,
# python 2
if not os.path.isfile(filepath):
f = open(filepath, 'w')
# python 3, x opens for exclusive creation, failing if the file already exists
try:
f = open(filepath, 'wx')
except IOError:
print 'file already exists'
파일 잠금이 필요한 경우 다른 문제입니다.
당신은 이것을 시도 할 수 있습니다 (더 안전합니다) :
try:
# http://effbot.org/zone/python-with-statement.htm
# 'with' is safer to open a file
with open('whatever.txt') as fh:
# Do something with 'fh'
except IOError as e:
print("({})".format(e))
출력은 다음과 같습니다.
([Errno 2] 해당 파일이나 디렉토리가 없습니다 : 'whatever.txt')
그런 다음 결과에 따라 프로그램을 계속 실행하거나 원하는 경우 코드를 중지 할 수 있습니다.
항상 try
및 except
문을 사용하는 것이 좋지만 다음과 같은 몇 가지 가능성이 있습니다 (내 개인적으로 os.access
사용).
파일을 열어보십시오.
파일을 열면 항상 파일의 존재 여부를 확인합니다. 다음과 같이 함수를 만들 수 있습니다.
def File_Existence(filepath):
f = open(filepath)
return True
False이면, 이후 버전의 Python에서 처리되지 않은 IOError 또는 OSError로 실행이 중지됩니다. 예외를 잡으려면 try except 절을 사용해야합니다. 물론, 당신은 항상 try
except 문을 사용할 수 있습니다. (감사합니다 hsandt 나를 생각하게 만드십시오) :
def File_Existence(filepath):
try:
f = open(filepath)
except IOError, OSError: # Note OSError is for later versions of Python
return False
return True
os.path.exists(path)
사용 :
이것은 당신이 지정한 것의 존재를 검사 할 것입니다. 그러나 파일 및 디렉토리를 확인하므로 사용 방법에주의하십시오.
import os.path
>>> os.path.exists("this/is/a/directory")
True
>>> os.path.exists("this/is/a/file.txt")
True
>>> os.path.exists("not/a/directory")
False
os.access(path, mode)
사용 :
파일에 대한 액세스 권한이 있는지 여부를 확인합니다. 권한을 확인합니다. os.py 문서를 기반으로 os.F_OK
를 입력하면 경로 존재 여부를 확인합니다. 그러나이를 사용하면 보안 허점이 생길 수 있습니다. 누군가가 권한 확인과 파일 열기 사이의 시간을 사용하여 파일을 공격 할 수 있기 때문입니다. 대신 권한을 확인하는 대신 파일을 열려면 직접 이동해야합니다. ( EAFP vs LBYP ). 나중에 파일을 열지 않고 파일의 존재 여부 만 확인하면이 파일을 사용할 수 있습니다.
어쨌든, 여기 :
>>> import os
>>> os.access("/is/a/file.txt", os.F_OK)
True
또한 파일의 존재 여부를 확인할 수없는 두 가지 방법이 있음을 언급해야합니다. 문제는 permission denied
또는 no such file or directory
가됩니다. IOError
을 잡으면 IOError as e
(내 첫 번째 옵션처럼)을 설정 한 다음 print(e.args)
을 입력하면 문제를 확인할 수 있습니다. 나는 그것이 도움이되기를 바랍니다! :)
날짜 : 2017-12-04
가능한 모든 해결책이 다른 대답에 나열되어 있습니다.
파일이 존재 하는지를 확인하는 직관적이고 논쟁 할 수있는 방법은 다음과 같습니다.
import os
os.path.isfile('~/file.md') # Returns True if exists, else False
# additionaly check a dir
os.path.isdir('~/folder') # Returns True if the folder exists, else False
# check either a dir or a file
os.path.exists('~/file')
참조 용 철저한 치트 시트를 만들었습니다.
#os.path methods in exhaustive cheatsheet
{'definition': ['dirname',
'basename',
'abspath',
'relpath',
'commonpath',
'normpath',
'realpath'],
'operation': ['split', 'splitdrive', 'splitext',
'join', 'normcase'],
'compare': ['samefile', 'sameopenfile', 'samestat'],
'condition': ['isdir',
'isfile',
'exists',
'lexists'
'islink',
'isabs',
'ismount',],
'expand': ['expanduser',
'expandvars'],
'stat': ['getatime', 'getctime', 'getmtime',
'getsize']}
또한 os.access()
:
if os.access("myfile", os.R_OK):
with open("myfile") as fp:
return fp.read()
권한 ( doc )을 테스트하기위한 플래그는 R_OK
, W_OK
및 X_OK
입니다.
파일을 여는 데 필요한 경우 다음 기술 중 하나를 사용할 수 있습니다.
>>> with open('somefile', 'xt') as f: #Using the x-flag, Python3.3 and above
... f.write('Hello\n')
>>> if not os.path.exists('somefile'):
... with open('somefile', 'wt') as f:
... f.write("Hello\n")
... else:
... print('File already exists!')
업데이트
혼란을 피하기 위해 내가 얻은 답을 바탕으로, 현재 대답은 파일 또는 주어진 이름의 디렉토리를 찾습니다.
if os.path.isfile(path_to_file):
try:
open(path_to_file)
pass
except IOError as e:
print "Unable to open file"
예외 발생은 프로그램에서 흐름 제어를위한 허용 가능한 Python 접근 방식으로 간주됩니다. IOErrors가있는 누락 된 파일 처리를 고려하십시오. 이 상황에서 파일이 있지만 사용자에게 읽기 권한이없는 경우 IOError 예외가 발생합니다.
try:
없이 Brian의 제안을 작성할 수 있습니다.
from contextlib import suppress
with suppress(IOError), open('filename'):
process()
suppress
은 Python 3.4의 일부입니다. 이전 버전에서는 자신 만의 억지력을 빠르게 작성할 수 있습니다.
from contextlib import contextmanager
@contextmanager
def suppress(*exceptions):
try:
yield
except exceptions:
pass
이미 다른 목적으로 NumPy를 가져온 경우 pathlib
, os
, paths
등과 같은 다른 라이브러리를 가져올 필요가 없습니다.
import numpy as np
np.DataSource().exists("path/to/your/file")
이것은 존재 여부에 따라 true 또는 false를 반환합니다.
다음 세 가지 방법을 따를 수 있습니다.
주 1 : 파일에만 사용되는
os.path.isfile
import os.path
os.path.isfile(filename) # True if file exists
os.path.isfile(dirname) # False if directory exists
주 2 : 파일과 디렉토리 모두에 사용되는
os.path.exists
import os.path
os.path.exists(filename) # True if file exists
os.path.exists(dirname) #True if directory exists
pathlib.Path
메소드 (Python 3+에 포함됨, Python 2 용 pip로 설치 가능)
from pathlib import Path
Path(filename).exists()
다른 답변에 정확히 반영되지 않은 약간의 변형을 추가합니다.
이것은 file_path
가 None
이거나 빈 문자열 인 경우를 처리합니다.
def file_exists(file_path):
if not file_path:
return False
Elif not os.path.isfile(file_path):
return False
else:
return True
Shahbaz에서 제안을 기반으로 변형 추가
def file_exists(file_path):
if not file_path:
return False
else:
return os.path.isfile(file_path)
Peter Wood의 제안을 기반으로 변형 추가
def file_exists(file_path):
return file_path and os.path.isfile(file_path):
나는 약 10 년 동안 있었던 패키지의 저자이며,이 질문에 직접적으로 대처하는 기능을 가지고있다. 기본적으로 비 Windows 시스템에 있다면 Popen
을 사용하여 find
에 액세스합니다. 그러나 Windows를 사용하는 경우 find
을 효율적인 파일 시스템 워커로 복제합니다.
코드 자체는 try
블록을 사용하지 않습니다 ... 운영 체제를 결정할 때를 제외하고 "유닉스"스타일 find
또는 손으로 작성한 find
로 안내합니다. 타이밍 테스트에 따르면 try
은 OS를 결정하는 속도가 더 빠르기 때문에 하나만 사용했습니다 (그러나 아무데도 사용하지 않았습니다).
>>> import pox
>>> pox.find('*python*', type='file', root=pox.homedir(), recurse=False)
['/Users/mmckerns/.python']
그리고 의사 ...
>>> print pox.find.__doc__
find(patterns[,root,recurse,type]); Get path to a file or directory
patterns: name or partial name string of items to search for
root: path string of top-level directory to search
recurse: if True, recurse down from root directory
type: item filter; one of {None, file, dir, link, socket, block, char}
verbose: if True, be a little verbose about the search
On some OS, recursion can be specified by recursion depth (an integer).
patterns can be specified with basic pattern matching. Additionally,
multiple patterns can be specified by splitting patterns with a ';'
For example:
>>> find('pox*', root='..')
['/Users/foo/pox/pox', '/Users/foo/pox/scripts/pox_launcher.py']
>>> find('*shutils*;*init*')
['/Users/foo/pox/pox/shutils.py', '/Users/foo/pox/pox/__init__.py']
>>>
구현 방법은 다음과 같습니다. https://github.com/uqfoundation/pox/blob/89f90fb308f285ca7a62eabe2c38acb87e89dad9/pox/shutils.py#L190
다음은 Linux 명령 행 환경을위한 1 행 Python 명령입니다. 나는 이처럼 뜨거운 배쉬 녀석이 아니기 때문에 이것을 아주 잘 찾는다.
python -c "import os.path; print os.path.isfile('/path_to/file.xxx')"
이것이 도움이되기를 바랍니다.
try 문을 사용하지 않고 파일이 있는지 어떻게 확인합니까?
2016 년에도 파일이 존재하는지 파일인지 확인하는 가장 쉬운 방법입니다.
import os
os.path.isfile('./file.txt') # Returns True if exists, else False
isfile
은 실제로 내부적으로 os.stat
및 stat.S_ISREG(mode)
을 사용하는 도우미 방법입니다. 이 os.stat
는 파일, 디렉토리, 소켓, 버퍼 등에 대한 자세한 정보를 제공하는 하위 수준의 방법입니다. 여기에서 os.stat에 대한 자세한 정보
참고 : 그러나이 방법은 파일을 어떤 식 으로든 잠그지 않으므로 코드가 "사용 시간 확인 시간 (TOCTTOU) 버그.
따라서 예외를 발생시키는 것은 프로그램에서 흐름 제어를 위해 허용 가능한 파이썬 방식으로 간주됩니다. 그리고 if
문 ( 단지 조언 ) 대신 IOErrors로 누락 된 파일을 처리하는 것을 고려해야합니다.
파이썬의 "OS"라이브러리를 사용할 수 있습니다 :
>>> import os
>>> os.path.exists("C:\\Users\\####\\Desktop\\test.txt")
True
>>> os.path.exists("C:\\Users\\####\\Desktop\\test.tx")
False
import os.path
def isReadableFile(file_path, file_name):
full_path = file_path + "/" + file_name
try:
if not os.path.exists(file_path):
print "File path is invalid."
return False
Elif not os.path.isfile(full_path):
print "File does not exist."
return False
Elif not os.access(full_path, os.R_OK):
print "File cannot be read."
return False
else:
print "File can be read."
return True
except IOError as ex:
print "I/O error({0}): {1}".format(ex.errno, ex.strerror)
except Error as ex:
print "Error({0}): {1}".format(ex.errno, ex.strerror)
return False
#------------------------------------------------------
path = "/usr/khaled/documents/puzzles"
fileName = "puzzle_1.txt"
isReadableFile(path, fileName)
다음 open 메소드를 사용하여 파일이 존재하는지 + 읽을 수 있는지 확인할 수 있습니다.
open(inputFile, 'r')
import os
path = /path/to/dir
root,dirs,files = os.walk(path).next()
if myfile in files:
print "yes it exists"
여러 파일을 확인할 때 유용합니다. 또는 기존 목록과 설정된 교차/차감을 수행하려고합니다.
파일이 있는지 확인하려면,
from sys import argv
from os.path import exists
script, filename = argv
target = open(filename)
print "file exists: %r" % exists(filename)
Os.listdir을 사용하여 파일이 특정 디렉토리에 있는지 확인할 수 있습니다.
import os
if 'file.ext' in os.listdir('dirpath'):
#code
import os
# for testing purpose args defaulted to current folder & file.
# returns True if file found
def file_exists(FOLDER_PATH='../', FILE_NAME=__file__):
return os.path.isdir(FOLDER_PATH) \
and os.path.isfile(os.path.join(FOLDER_PATH, FILE_NAME))
기본적으로 폴더 검사 후 os.path.join 를 사용하여 적절한 디렉토리 구분 기호로 파일을 검사합니다.
당신은 확실히 이것을 사용해야합니다.
from os.path import exists
if exists("file") == True:
print "File exists."
Elif exists("file") == False:
print "File doesn't exist."
아마도 필요하지는 않지만 그렇다면 여기에 몇 가지 코드가 있습니다.
import os
def file_exists(path, filename):
for file_or_folder in os.listdir(path):
if file_or_folder == filename:
return True
return False