How to check file size in python?

2018-12-31 12:23发布

I am writing a Python script in Windows. I want to do something based on the file size. For example, if the size is greater than 0, I will send an email to somebody, otherwise continue to other things.

How do I check the file size?

标签: python
8条回答
骚的不知所云
2楼-- · 2018-12-31 13:26

Using pathlib (added in Python 3.4 and available on PyPI)...

from pathlib import Path
file = Path() / 'doc.txt'  # or Path('./doc.txt')
size = file.stat().st_size

This is really only an interface around os.stat, but using pathlib provides an easy way to access other file related operations.

查看更多
闭嘴吧你
3楼-- · 2018-12-31 13:27

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)
查看更多
登录 后发表回答