How to get file size in Python? 获取文件大小Python

How to get file size in Python?

We can follow different approaches to get the file size in Python. It’s important to get the file size in Python to monitor file size or in case of ordering files in the directory according to file size. 

Method 1: Using getsize function of os.path module

This function takes a file path as an argument and it returns the file size (bytes). 

Example:

 

# approach 1
# using getsize function os.path module
import os
 
file_size = os.path.getsize('d:/file.jpg')
print("File Size is :", file_size, "bytes")

 

Method 2: Using stat function of the OS module

This function takes a file path as an argument (string or file object) and returns statistical details about file path given as input. 

Example:

# approach 2
# using stat function of os module
import os
 
file_size = os.stat('d:/file.jpg')
print("Size of file :", file_size.st_size, "bytes")

 

Method 3: Using File Object

To get the file size, follow these steps –

  1. Use the open function to open the file and store the returned object in a variable.  When the file is opened, the cursor points to the beginning of the file.
  2. File object has seek method used to set the cursor to the desired location. It accepts 2 arguments – start location and end location. To set the cursor at the end location of the file use method os.SEEK_END.
  3. File object has tell method that can be used to get the current cursor location which will be equivalent to the number of bytes cursor has moved. So this method actually returns the size of the file in bytes.
# approach 3
# using file object
 
# open file
file = open('d:/file.jpg')
 
# get the cursor positioned at end
file.seek(0, os.SEEK_END)
 
# get the current position of cursor
# this will be equivalent to size of file
print("Size of file is :", file.tell(), "bytes")

 

Method 4: Using Pathlib Module

The stat() method of the Path object returns st_mode, st_dev, etc. properties of a file. And, st_size attribute of the stat method gives the file size in bytes.

# approach 4
# using pathlib module
from pathlib import Path
 
# open file
Path(r'd:/file.jpg').stat()
 
# getting file size
file=Path(r'd:/file.jpg').stat().st_size
 
# display the size of the file
print("Size of file is :", file, "bytes")
 
# this code was contributed by debrc

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(52)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-12-02 2020年成人高考专升本高数(一)考试真题及答案 ​ 做题进度
2015-12-02 hierarchy中展开所有子项
2015-12-02 unity3d5.2.3中 调整视角
2015-12-02 NuGet在2015中的使用
2014-12-02 TeeChart.Direct2D.dll的使用
点击右上角即可分享
微信分享提示