티스토리 뷰

반응형

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

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

 

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

Getting file size in Python?

파이썬에서 파일 크기 가져오기

 문제 내용 

Is there a built-in function for getting the size of a file object in bytes? I see some people do something like this:

파일의 크기를 바이트 단위로 가져오는 기능이 내장되어 있나요? 어떤 사람들은 이런 짓을 하기도 해요
def getSize(fileobject):
    fileobject.seek(0,2) # move the cursor to the end of the file
    size = fileobject.tell()
    return size

file = open('myfile.bin', 'rb')
print getSize(file)

 

But from my experience with Python, it has a lot of helper functions so I'm guessing maybe there is one built-in.

하지만 Python을 사용한 경험으로 볼 때, 파이썬에는 많은 도우미 기능을 가지고 있기 때문에 아마도 내장된 기능이 하나 있을 것 같습니다.

 

 

 

 높은 점수를 받은 Solution 

Use os.path.getsize(path) which will

다음과 같은 os.path.getsize(경로)를 사용합니다.

 

Return the size, in bytes, of path. Raise OSError if the file does not exist or is inaccessible.

경로의 크기(바이트)를 반환합니다. 파일이 없거나 액세스할 수 없는 경우 OS 오류를 발생시킵니다.
import os
os.path.getsize('C:\\Python27\\Lib\\genericpath.py')

 

Or use os.stat(path).st_size

또는 os.stat(경로).st_size를 사용합니다.
import os
os.stat('C:\\Python27\\Lib\\genericpath.py').st_size 

 

Or use Path(path).stat().st_size (Python 3.4+)

또는 Path(path).stat().st_size(Python 3.4+)를 사용합니다.
from pathlib import Path
Path('C:\\Python27\\Lib\\genericpath.py').stat().st_size

 

 

 가장 최근 달린 Solution 

You may use os.stat() function, which is a wrapper of system call stat():

시스템 호출 stat()의 래퍼인 os.stat() 함수를 사용할 수 있습니다.
import os

def getSize(filename):
    st = os.stat(filename)
    return st.st_size

 

 

출처 : https://stackoverflow.com/questions/6591931/getting-file-size-in-python

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