프로그래밍 언어/Python
Python에서 파일 객체의 크기를 바이트 단위로 가져 오는 내장 함수
Rateye
2021. 9. 2. 11:55
728x90
반응형
질문 : Python에서 파일 크기를 얻습니까?
파일 객체의 크기를 바이트 단위로 가져 오는 내장 함수가 있습니까? 나는 어떤 사람들이 다음과 같이하는 것을 본다.
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)
그러나 Python에 대한 경험상 많은 도우미 함수가 있으므로 아마도 하나의 내장 기능이 있다고 생각합니다.
답변
os.path.getsize(path)
를 사용하면
path 의 크기 (바이트)를 반환합니다. 파일이 없거나 액세스 할 수없는 경우 OSError
import os
os.path.getsize('C:\\Python27\\Lib\\genericpath.py')
import os
os.stat('C:\\Python27\\Lib\\genericpath.py').st_size
또는 Path(path).stat().st_size
(Python 3.4 이상)를 사용하십시오.
from pathlib import Path
Path('C:\\Python27\\Lib\\genericpath.py').stat().st_size
출처 : https://stackoverflow.com/questions/6591931/getting-file-size-in-python
728x90
반응형