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.
В этом посте мы обсудим, как получить размер файла в Python.
1. Использование os.stat()
функция
Стандартным решением для получения статуса файла является использование os.stat()
Функция Python. Он возвращает stat_result
объект, который имеет st_size
атрибут, содержащий размер файла в байтах.
import os stats = os.stat(‘pathtofilefilename.ext’) print(stats.st_size) |
2. Использование Path.stat()
функция
В качестве альтернативы с Python 3.4 вы можете использовать Path.stat()
функция от pathlib
модуль. Это похоже на os.stat()
функция и возвращает stat_result
объект, содержащий информацию об указанном пути.
from pathlib import Path f = Path(‘pathtofilefilename.ext’) size = f.stat().st_size print(size) |
3. Использование os.path.getsize()
функция
Еще один хороший вариант — использовать os.path.getsize()
функция для получения размера указанного пути в байтах.
import os size = os.path.getsize(‘pathtofilefilename.ext’) print(size) |
4. Использование seek()
функция
Здесь идея состоит в том, чтобы открыть файл в режиме только для чтения и установить в конце текущую позицию файлового дескриптора. Это можно сделать с помощью seek()
функция, которая возвращает текущую позицию курсора в байтах, начиная с начала.
import os with open(‘pathtofilefilename.ext’, ‘r’) as f: size = f.seek(0, os.SEEK_END) print(size) |
Это все, что касается получения размера файла в Python.
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования
In this article, we will discuss different ways to get file size in human-readable formats like Bytes, Kilobytes (KB), MegaBytes (MB), GigaBytes(GB) etc.
Different ways to get file size in Bytes
Get file size in bytes using os.path.getsize()
os.path.getsize(path)
It accepts the file path as an argument and returns the size of a file at the given path in bytes.
If the file doesn’t exist at the given path or it is inaccessible, then it raises an os.error. Therefore, always check that file exist or not before calling this function.
Advertisements
Let’s use this function to get the size of a file in bytes,
import os def get_file_size_in_bytes(file_path): """ Get size of file at given path in bytes""" size = os.path.getsize(file_path) return size file_path = 'big_file.csv' size = get_file_size_in_bytes(file_path) print('File size in bytes : ', size)
Output:
Frequently Asked:
- Python : How to delete a directory recursively using shutil.rmtree()
- Find the smallest file in a directory using python
- Python: Search strings in a file and get line numbers of lines containing the string
- Python: Three ways to check if a file is empty
File size in bytes : 166908268
Get file size in bytes using os.stat().st_size
Python’s os module provides a function to get the file statistics,
os.stat(path, *, dir_fd=None, follow_symlinks=True)
It accepts file path (a string) as an argument and returns an object of the structure stat, which contains various attributes about the file at a given path. One of the attributes is st_size, which has the size of the file in bytes.
Let’s use this function to get the size of a file in bytes,
import os def get_file_size_in_bytes_2(file_path): """ Get size of file at given path in bytes""" # get statistics of the file stat_info = os.stat(file_path) # get size of file in bytes size = stat_info.st_size return size file_path = 'big_file.csv' size = get_file_size_in_bytes_2(file_path) print('File size in bytes : ', size)
Output:
Latest Python — Video Tutorial
File size in bytes : 166908268
Get file size in bytes using pathlib.Path.stat().st_size
Let’s use pathlib module to get the size of a file in bytes,
from pathlib import Path def get_file_size_in_bytes_3(file_path): """ Get size of file at given path in bytes""" # get file object file_obj = Path(file_path) # Get file size from stat object of file size = file_obj.stat().st_size return size file_path = 'big_file.csv' size = get_file_size_in_bytes_3(file_path) print('File size in bytes : ', size)
Output:
File size in bytes : 166908268
In all the above techniques, we got the file size in bytes. What if we want file size in human-readable format like, KilloBytes, Megabytes or GigaBytes etc.
Get file size in human-readable units like kilobytes (KB), Megabytes (MB) or GigaBytes (GB)
1 KilloByte == 1024 Bytes
1 Megabyte == 1024*1024 Bytes
1 GigaByte == 1024*1024*1024 Bytes
We have created a function to convert the bytes into kilobytes (KB), Megabytes (MB) or GigaBytes (GB) i.e.
import enum # Enum for size units class SIZE_UNIT(enum.Enum): BYTES = 1 KB = 2 MB = 3 GB = 4 def convert_unit(size_in_bytes, unit): """ Convert the size from bytes to other units like KB, MB or GB""" if unit == SIZE_UNIT.KB: return size_in_bytes/1024 elif unit == SIZE_UNIT.MB: return size_in_bytes/(1024*1024) elif unit == SIZE_UNIT.GB: return size_in_bytes/(1024*1024*1024) else: return size_in_bytes
Let’s create a function to get the file size in different size units. This function internally uses to the above function to convert bytes into given size unit,
import os def get_file_size(file_name, size_type = SIZE_UNIT.BYTES ): """ Get file in size in given unit like KB, MB or GB""" size = os.path.getsize(file_name) return convert_unit(size, size_type)
Let’s use this function to get the size of a given file in KB, MB or GB,
Get size of a file in Kilobyte i.e. KB
file_path = 'big_file.csv' # get file size in KB size = get_file_size(file_path, SIZE_UNIT.KB) print('Size of file is : ', size , 'KB')
Output:
Size of file is : 162996.35546875 KB
Get size of a file in Megabyte i.e. MB
file_path = 'big_file.csv' # get file size in MB size = get_file_size(file_path, SIZE_UNIT.MB) print('Size of file is : ', size , 'MB')
Output:
Size of file is : 159.17612838745117 MB
Get size of a file in Gigabyte i.e. GB
file_path = 'big_file.csv' # get file size in GB size = get_file_size(file_path, SIZE_UNIT.GB) print('Size of file is : ', size , 'GB')
Output:
Size of file is : 0.15544543787837029 GB
Check if file exists before checking for the size of the file
If the file does not exist at the given path, then all the above created function to get file size can raise Error. Therefore we should first check if file exists or not, if yes then only check its size,
import os file_name = 'dummy_file.txt' if os.path.exists(file_name): size = get_file_size(file_name) print('Size of file in Bytes : ', size) else: print('File does not exist')
Output:
File does not exist
As file ‘dummy_file.txt’ does not exist, so we can not calculate its size.
The complete example is as follows,
import os import enum from pathlib import Path def get_file_size_in_bytes(file_path): """ Get size of file at given path in bytes""" size = os.path.getsize(file_path) return size def get_file_size_in_bytes_2(file_path): """ Get size of file at given path in bytes""" # get statistics of the file stat_info = os.stat(file_path) # get size of file in bytes size = stat_info.st_size return size def get_file_size_in_bytes_3(file_path): """ Get size of file at given path in bytes""" # get file object file_obj = Path(file_path) # Get file size from stat object of file size = file_obj.stat().st_size return size # Enum for size units class SIZE_UNIT(enum.Enum): BYTES = 1 KB = 2 MB = 3 GB = 4 def convert_unit(size_in_bytes, unit): """ Convert the size from bytes to other units like KB, MB or GB""" if unit == SIZE_UNIT.KB: return size_in_bytes/1024 elif unit == SIZE_UNIT.MB: return size_in_bytes/(1024*1024) elif unit == SIZE_UNIT.GB: return size_in_bytes/(1024*1024*1024) else: return size_in_bytes def get_file_size(file_name, size_type = SIZE_UNIT.BYTES ): """ Get file in size in given unit like KB, MB or GB""" size = os.path.getsize(file_name) return convert_unit(size, size_type) def main(): print('*** Get file size in bytes using os.path.getsize() ***') file_path = 'big_file.csv' size = get_file_size_in_bytes(file_path) print('File size in bytes : ', size) print('*** Get file size in bytes using os.stat().st_size ***') file_path = 'big_file.csv' size = get_file_size_in_bytes_2(file_path) print('File size in bytes : ', size) print('*** Get file size in bytes using pathlib.Path.stat().st_size ***') file_path = 'big_file.csv' size = get_file_size_in_bytes_3(file_path) print('File size in bytes : ', size) print('*** Get file size in human readable format like in KB, MB or GB ***') print('Get file size in Kilobyte i.e. KB') file_path = 'big_file.csv' # get file size in KB size = get_file_size(file_path, SIZE_UNIT.KB) print('Size of file is : ', size , 'KB') print('Get file size in Megabyte i.e. MB') file_path = 'big_file.csv' # get file size in MB size = get_file_size(file_path, SIZE_UNIT.MB) print('Size of file is : ', size , 'MB') print('Get file size in Gigabyte i.e. GB') file_path = 'big_file.csv' # get file size in GB size = get_file_size(file_path, SIZE_UNIT.GB) print('Size of file is : ', size , 'GB') print('*** Check if file exists before checking for the size of a file ***') file_name = 'dummy_file.txt' if os.path.exists(file_name): size = get_file_size(file_name) print('Size of file in Bytes : ', size) else: print('File does not exist') if __name__ == '__main__': main()
Output:
*** Get file size in bytes using os.path.getsize() *** File size in bytes : 166908268 *** Get file size in bytes using os.stat().st_size *** File size in bytes : 166908268 *** Get file size in bytes using pathlib.Path.stat().st_size *** File size in bytes : 166908268 *** Get file size in human readable format like in KB, MB or GB *** Get file size in Kilobyte i.e. KB Size of file is : 162996.35546875 KB Get file size in Megabyte i.e. MB Size of file is : 159.17612838745117 MB Get file size in Gigabyte i.e. GB Size of file is : 0.15544543787837029 GB *** Check if file exists before checking for the size of a file *** File does not exist