The other answers work for real files, but if you need something that works for “file-like objects”, try this:
# f is a file-like object.
f.seek(0, os.SEEK_END)
size = f.tell()
It works for real files and StringIO’s, in my limited testing. (Python 2.7.3.) The “file-like object” API isn’t really a rigorous interface, of course, but the API documentation suggests that file-like objects should support seek()
and tell()
.
Edit
Another difference between this and os.stat()
is that you can stat()
a file even if you don’t have permission to read it. Obviously the seek/tell approach won’t work unless you have read permission.
Edit 2
At Jonathon’s suggestion, here’s a paranoid version. (The version above leaves the file pointer at the end of the file, so if you were to try to read from the file, you’d get zero bytes back!)
# 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)
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
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:
Python3
import
os
file_size
=
os.path.getsize(
'd:/file.jpg'
)
print
(
"File Size is :"
, file_size,
"bytes"
)
Output:
File Size is : 218 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:
Python3
import
os
file_size
=
os.stat(
'd:/file.jpg'
)
print
(
"Size of file :"
, file_size.st_size,
"bytes"
)
Output:
Size of file : 218 bytes
Method 3: Using File Object
To get the file size, follow these steps –
- 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.
- 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.
- 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.
Example:
Python3
file
=
open
(
'd:/file.jpg'
)
file
.seek(
0
, os.SEEK_END)
print
(
"Size of file is :"
,
file
.tell(),
"bytes"
)
Output:
Size of file is : 218 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.
Example:
Python3
from
pathlib
import
Path
Path(r
'd:/file.jpg'
).stat()
file
=
Path(r
'd:/file.jpg'
).stat().st_size
print
(
"Size of file is :"
,
file
,
"bytes"
)
Output:
Size of file is : 218 bytes
Last Updated :
21 Jan, 2021
Like Article
Save Article
Время чтения 2 мин.
Python stat() — это встроенный модуль OS, который имеет два метода, которые возвращают размер файла. Модуль OS в Python предоставляет функции для взаимодействия с операционной системой. Он входит в стандартные служебные модули Python. Модуль os обеспечивает портативный подход к использованию функций, зависящих от операционной системы.
Содержание
- Получение размера файла в Python
- Python os.path.getsize()
- Python os.stat()
- Python path.stat().st_mode
Чтобы получить размер файла в Python, мы можем использовать один из следующих трех способов:
- Python os.path.getsize()
- Python os.stat()
- Python path.stat().st_mode.
Python os.path.getsize()
Функция os.path.getsize() возвращает размер в байтах. Вызовет OSError, если файл не существует или недоступен.
См. следующий код.
import os file_name = “npfile.txt” file_size = os.path.getsize(file_name) print(f‘File Size in Bytes is {file_size}’) print(f‘File Size in MegaBytes is {file_size /(1024 * 1024)}’) |
Выход:
File Size in Bytes is 42 File Size in MegaBytes is 4.00543212890625e–05 |
Сначала мы определили файл, а затем получили его размер с помощью функции os.path.getsize(), которая возвращает размер файла в байтах, а затем в последней строке мы преобразовали размер в байтах в размер в МБ.
Python os.stat()
Метод os.stat() в Python выполняет системный вызов stat() по указанному пути. Метод stat() используется для получения статуса указанного пути. Затем мы можем получить его атрибут st_size, чтобы получить размер файла в байтах. Метод stat() принимает в качестве аргумента имя файла и возвращает кортеж, содержащий информацию о файле.
import os file_name = “npfile.txt” file_stats = os.stat(file_name) print(file_stats) print(f‘File Size in Bytes is {file_stats.st_size}’) print(f‘File Size in MegaBytes is {file_stats.st_size /(1024 * 1024)}’) |
Выход:
os.stat_result(st_mode=33188, st_ino=75203319, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=42, st_atime=1589517754, st_mtime=1589517753, st_ctime=1589517753) File Size in Bytes is 42 File Size in MegaBytes is 4.00543212890625e–05 |
Из вывода вы можете видеть, что мы получили кортеж, полный информации о файле. Затем мы получили доступ к определенному свойству, называемому st_size, чтобы получить размер файла, а затем преобразовать размер в МБ или мегабайты.
Если вы внимательно посмотрите на метод stat(), мы можем передать еще два параметра: dir_fd и follow_symlinks. Однако они не реализованы для macOS.
Python path.stat().st_mode
Функция Python path.stat() возвращает объект os.stat_result, содержащий информацию об этом пути, подобно os.stat(). Результат просматривается при каждом вызове этого метода.
См. следующий код.
from pathlib import Path file_name = “npfile.txt” file_size = Path(file_name).stat().st_size print(f‘File Size in Bytes is {file_size}’) print(f‘File Size in MegaBytes is {file_size /(1024 * 1024)}’) |
Выход:
File Size in Bytes is 42 File Size in MegaBytes is 4.00543212890625e–05 |
Мы импортировали модуль pathlib и использовали Path.state().st_size для получения размера файла.
Итак, мы рассмотрели 3 метода, как узнать размер файла в Python.
Получить размер файла в байтах.
Синтаксис:
import os.path os.path.getsize(path)
Параметры:
path
– путь к файлу или каталогу.
Возвращаемое значение:
int
– размер файла в байтах.
Описание:
Функция getsize()
модуля os.path
возвращает размер файла в байтах, указанного в path
. Если path
не существует или недоступен, то поднимается исключение OSError
.
Аргумент path
может принимать байтовые или текстовые строки. Функция os.path.getsize()
может принимать объект, представляющий путь к файловой системе, например такой как pathlib.PurePath
.
Примеры использования:
>>> import os.path >>> os.path.getsize('/home/docs-python/os.path.txt') # 11828 >>> os.path.getsize(b'/home/docs-python/os.path.txt') # 11828 >>> os.path.getsize('/home/docs-python') # 4096
In this tutorial, you’ll learn how to get file size in Python.
Whenever we work with files, sometimes we need to check file size before performing any operation. For example, if you are trying to copy content from one file into another file. In this case, we can check if the file size is greater than 0 before performing the file copying operation.
In this article, We will use the following three methods of an OS and pathlib module to get file size.
os.path module:
os.path.getsize('file_path')
: Return the file size in bytes.os.stat(file).st_size
: Return the file size in bytes
Pathlib module:
pathlib.Path('path').stat().st_size
: Return the file size in bytes.
os.path.getsize() Method to Check File Size
For example, you want to read a file to analyze the sales data to prepare a monthly report, but before performing this operation we want to check whether the file contains any data.
The os.path module has some valuable functions on pathnames. Here we will see how to use the os.path
module to check the file size.
- Important the os.path module
This module helps us to work with file paths and directories in Python. Using this module, we can access and manipulate paths
- Construct File Path
A file path defines the location of a file or folder in the computer system. There are two ways to specify a file path.
Absolute path: which always begins with the root folder. The absolute path includes the complete directory list required to locate the file. For example,
/user/Pynative/data/sales.txt
is an absolute path to discover the sales.txt. All of the information needed to find the file is contained in the path string.Relative path: which is relative to the program’s current working directory.
To maintain uniformity across the operating system, use the forward-slash (
/
) to separate the path. It’ll work across Windows, macOS, and Unix-based systems, including Linux. - Use os.path.getsize() function
Use the
os.path.getsize('file_path')
function to check the file size. Pass the file name or file path to this function as an argument. This function returns file size in bytes. It raises OSError if the file does not exist or is inaccessible.
Example To Get File Size
import os.path
# file to check
file_path = r'E:/demos/account/sales.txt'
sz = os.path.getsize(file_path)
print(f'The {file_path} size is', sz, 'bytes')
Output:
E:/demos/account/sales.txt size is 10560 bytes
Get File Size in KB, MB, or GB
- First, get the file size using the getsize() function.
- Next, convert bytes to KB or MB.
Use the following example to convert the file size in KB, MB, or GB.
import os.path
# calculate file size in KB, MB, GB
def convert_bytes(size):
""" Convert bytes to KB, or MB or GB"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if size < 1024.0:
return "%3.1f %s" % (size, x)
size /= 1024.0
f_size = os.path.getsize(r'E:/demos/account/sales.txt')
x = convert_bytes(f_size)
print('file size is', x)
Output:
file size is 10.3 KB
os.stat() Method to Check File Size
The os.stat()
method returns the statistics of a file such as metadata of a file, creation or modification date, file size, etc.
- First, import the os module
- Next, use the
os.stat('file_path')
method to get the file statistics. - At the end, use the
st_size
attribute to get the file size.
Note: The os.path.getsize()
function internally uses the os.stat('path').st_size
.
Example:
import os
# get file statistics
stat = os.stat(r'E:/demos/account/sales.txt')
# get file size
f_size = stat.st_size
print('file size is', f_size, 'bytes')
Output:
file size is 10560 bytes
Pathlib Module to Get File Size
From Python 3.4 onwards, we can use the pathlib module, which provides a wrapper for most OS functions.
- Import pathlib module: Pathlib module offers classes and methods to handle filesystem paths and get data related to files for different operating systems.
- Next, Use the
pathlib.Path('path').stat().st_size
attribute to get the file size in bytes
Example:
import pathlib
# calculate file size in KB, MB, GB
def convert_bytes(size):
""" Convert bytes to KB, or MB or GB"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if size < 1024.0:
return "%3.1f %s" % (size, x)
size /= 1024.0
path = pathlib.Path(r'E:/demos/account/sales.txt')
f_size = path.stat().st_size
print('File size in bytes', f_size)
# you can skip this if you don't want file size in KB or MB
x = convert_bytes(f_size)
print('file size is', x)
Output:
file size is 10.3 KB
Get File Size of a File Object
Whenever we use file methods such as read() or a write(), we get a file object in return that represents a file.
Also, sometimes we receive a file object as an argument to a function, and we wanted to find a size of a file this file object is representing.
All the above solutions work for a file present on a disk, but if you want to find file size for file-like objects, use the below solution.
We will use the seek()
function to move the file pointer to calculate the file size. Let’s see the steps.
- Use the
open()
function to open a file in reading mode. When we open a file, the cursor always points to the start of the file. - Use the file seek() method to move the file pointer at the end of the file.
- Next, use the file
tell()
method to get the file size in bytes. Thetell()
method returns the current cursor location, equivalent to the number of bytes the cursor has moved, which is nothing but a file size in bytes.
Example:
# fp is a file object.
# read file
fp = open(r'E:/demos/account/sales.txt', 'r')
old_file_position = fp.tell()
# Moving the file handle to the end of the file
fp.seek(0, 2)
# calculates the bytes
size = fp.tell()
print('file size is', size, 'bytes')
fp.seek(old_file_position, 0)
Output:
file size is 10560 bytes
Sumary
In this article, We used the following three methods of an OS and pathlib module to get file size.
os.path module:
os.path.getsize('file_path')
: Return the file size in bytes.os.stat(file).st_size
: Return the file size in bytes
Pathlib module:
pathlib.Path('path').stat().st_size
: Return the file size in bytes.
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
- 15+ Topic-specific Exercises and Quizzes
- Each Exercise contains 10 questions
- Each Quiz contains 12-15 MCQ