파이썬에서 파일 크기를 확인하는 방법은 무엇입니까?
Windows에서 Python 스크립트를 작성하고 있습니다. 파일 크기에 따라 뭔가를하고 싶습니다. 예를 들어, 크기가 0보다 크면 누군가에게 이메일을 보내고 그렇지 않으면 다른 일을 계속합니다.
파일 크기는 어떻게 확인합니까?
를 사용 하고 결과 개체 os.stat
의 st_size
멤버를 사용 합니다.
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
>>> statinfo.st_size
926L
출력은 바이트 단위입니다.
사용 os.path.getsize
:
>>> import os
>>> b = os.path.getsize("/path/isa_005.mp3")
>>> b
2071611L
출력은 바이트 단위입니다.
다른 답변은 실제 파일에서 작동하지만 "파일과 유사한 객체"에 대해 작동하는 것이 필요하면 다음을 시도하십시오.
# f is a file-like object.
f.seek(0, os.SEEK_END)
size = f.tell()
제한된 테스트에서 실제 파일과 StringIO에서 작동합니다. (Python 2.7.3.) "파일 류 객체"API는 물론 엄격한 인터페이스가 아니지만 API 문서 에서는 파일 류 객체가 seek()
및 tell()
.
편집하다
이 사이 또 다른 차이점은 os.stat()
당신이 할 수 있다는 것입니다 stat()
당신이 그것을 읽을 수있는 권한이 파일이없는 경우에도 마찬가지입니다. 읽기 권한이 없으면 분명히 찾기 / 말하기 접근 방식이 작동하지 않습니다.
편집 2
Jonathon의 제안에 따라 편집증 버전이 있습니다. (위의 버전은 파일의 끝에 파일 포인터를 남겨두기 때문에 파일에서 읽으려고하면 0 바이트를 되찾게됩니다!)
# f is a file-like object.
old_file_position = f.tell()
f.seek(0, os.SEEK_END)
size = f.tell()
f.seek(old_file_position, os.SEEK_SET)
import os
def convert_bytes(num):
"""
this function will convert bytes to MB.... GB... etc
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0
def file_size(file_path):
"""
this function will return the file size
"""
if os.path.isfile(file_path):
file_info = os.stat(file_path)
return convert_bytes(file_info.st_size)
# Lets check the file size of MS Paint exe
# or you can use any file path
file_path = r"C:\Windows\System32\mspaint.exe"
print file_size(file_path)
결과:
6.1 MB
사용 pathlib
( 파이썬 3.4에서 추가 또는에 백 포트를 사용할 PyPI ) :
from pathlib import Path
file = Path() / 'doc.txt' # or Path('./doc.txt')
size = file.stat().st_size
이것은 실제로 주위의 인터페이스 os.stat
일 뿐이지 만를 사용 pathlib
하면 다른 파일 관련 작업에 쉽게 액세스 할 수 있습니다.
There is a bitshift
trick I use if i want to to convert from bytes
to any other unit. If you do a right shift by 10
you basically shift it by an order (multiple).
Example:
5GB are 5368709120 bytes
print (5368709120 >> 10) # 5242880 kilo Bytes (kB)
print (5368709120 >> 20 ) # 5120 Mega Bytes(MB)
print (5368709120 >> 30 ) # 5 Giga Bytes(GB)
Strictly sticking to the question, the python code (+ pseudo-code) would be:
import os
file_path = r"<path to your file>"
if os.stat(file_path).st_size > 0:
<send an email to somebody>
else:
<continue to other things>
#Get file size , print it , process it...
#Os.stat will provide the file size in (.st_size) property.
#The file size will be shown in bytes.
import os
fsize=os.stat('filepath')
print('size:' + fsize.st_size.__str__())
#check if the file size is less than 10 MB
if fsize.st_size < 10000000:
process it ....
참고URL : https://stackoverflow.com/questions/2104080/how-to-check-file-size-in-python
'Nice programing' 카테고리의 다른 글
한 분기에서 다른 분기로 커밋을 복사하는 방법은 무엇입니까? (0) | 2020.09.30 |
---|---|
속성 값으로 객체 배열에서 JavaScript 객체 가져 오기 [duplicate] (0) | 2020.09.30 |
문자열의 마지막 문자를 어떻게 얻을 수 있습니까? (0) | 2020.09.30 |
문자열에서 마지막 문자 제거 (0) | 2020.09.30 |
GitHub 오류 메시지-권한이 거부되었습니다 (공개 키). (0) | 2020.09.30 |