개발/파이썬

file과 open 함수의 차이점

맨날치킨 2023. 1. 27. 16:05
반응형

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

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

 

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

Python - When to use file vs open

Python - file과 open을 언제 사용해야 할까요?

 문제 내용 

What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5)

Python에서 file과 open의 차이점은 무엇인가요? 어떤 경우에 둘 중 어느 것을 사용해야 할까요? (예를 들어, 제가 Python 2.5를 사용한다면)

 

 

 

 높은 점수를 받은 Solution 

You should always use open().

항상 open()을 사용해야 합니다.

 

As the documentation states:

문서에 명시된 것처럼,

 

When opening a file, it's preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing "isinstance(f, file)").

파일을 열 때는 직접 생성자를 호출하는 대신 open()을 사용하는 것이 좋습니다. file은 주로 타입 테스트에 적합합니다(예: "isinstance(f, file)" 작성).

 

Also, file() has been removed since Python 3.0.

또한, file() 함수는 파이썬 3.0 이후로 삭제되었습니다.

 

 

 

 가장 최근 달린 Solution 

file() is a type, like an int or a list. open() is a function for opening files, and will return a file object.

file()는 int나 list와 같은 타입입니다. open()은 파일을 열기 위한 함수이며, 파일 객체를 반환합니다.

 

This is an example of when you should use open:

이것은 open을 사용해야 하는 예시입니다.
f = open(filename, 'r')
for line in f:
    process(line)
f.close()

 

This is an example of when you should use file:

다음은 파일을 사용해야 하는 경우의 예입니다.
class LoggingFile(file):
    def write(self, data):
        sys.stderr.write("Wrote %d bytes\n" % len(data))
        super(LoggingFile, self).write(data)

 

As you can see, there's a good reason for both to exist, and a clear use-case for both.

두 가지 함수(open(), file())가 존재하는 이유가 분명하고 각각에 대한 명확한 사용 사례가 있습니다.

 

 

 

출처 : https://stackoverflow.com/questions/112970/python-when-to-use-file-vs-open

반응형