티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Pythonic way to check if a file exists?

Python에서 파일이 존재하는지 확인하는 방법?

 문제 내용 

Which is the preferred way to check if a file exists and if not create it?

파일이 존재하는지 확인하고, 없으면 생성하는 좋은 방법이 있을까요?

 

 

 

 높은 점수를 받은 Solution 

To check if a path is an existing file:

경로가 존재하는지 확인하려면:

 

os.path.isfile(path)

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

경로가 심볼릭 링크를 따라가며 일반 파일인 경우 True를 반환합니다. 따라서 동일한 경로에서 islink()와 isfile() 모두 True일 수 있습니다.

 

 

 

 가장 최근 달린 Solution 

It seems to me that all other answers here (so far) fail to address the race-condition that occurs with their proposed solutions.

현재까지 여기서 제시된 다른 대답들은 제안된 솔루션으로 인해 발생하는 경쟁 조건에 대해 언급하지 못하고 있다고 생각됩니다.

 

Any code where you first check for the files existence, and then, a few lines later in your program, you create it, runs the risk of the file being created while you weren't looking and causing you problems (or you causing the owner of "that other file" problems).

파일 존재 여부를 먼저 확인한 다음 몇 줄 뒤에 생성하는 모든 코드는 파일이 당신이 주시하지 않을 때 생성되어 문제를 일으키거나 ("그 다른 파일"의 소유자로 인해 문제를 일으키는 경우도 있음) 문제를 일으킬 수 있습니다.

 

If you want to avoid this sort of thing, I would suggest something like the following (untested):

이러한 문제를 피하려면 다음과 같은 방법을 제안합니다 (테스트되지 않음):
import os

def open_if_not_exists(filename):
    try:
        fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    except OSError, e:
        if e.errno == 17:
            print e
            return None
        else:
            raise
    else:
        return os.fdopen(fd, 'w')

 

This should open your file for writing if it doesn't exist already, and return a file-object. If it does exists, it will print "Ooops" and return None (untested, and based solely on reading the python documentation, so might not be 100% correct).

이 방법은 파일이 아직 존재하지 않는 경우 파일을 쓰기 위해 열고 파일 객체를 반환합니다. 파일이 이미 존재하는 경우 "Ooops"를 출력하고 None을 반환합니다 (테스트되지 않았으며 Python 문서를 읽고 기반으로 작성되었기 때문에 100% 정확하지 않을 수 있습니다).

 

 

 

출처 : https://stackoverflow.com/questions/2259382/pythonic-way-to-check-if-a-file-exists

반응형
댓글
공지사항
최근에 올라온 글