Как получить расширение и размер файла в Python
Мы можем использовать функцию splitext() модуля os в Python, чтобы получить расширение файла. Эта функция разбивает путь к файлу на кортеж, имеющий два значения – корень и расширение.
Вот простая программа для получения расширения файла на Python.
- В первом примере мы напрямую распаковываем значения кортежа в две переменные.
- Обратите внимание, что файл .bashrc не имеет расширения. К имени файла добавляется точка, чтобы сделать его скрытым.
- В третьем примере в имени каталога есть точка.
Получение расширения файла с помощью модуля Pathlib
Мы также можем использовать модуль pathlib, чтобы получить расширение файла. Этот модуль был представлен в версии Python 3.4.
Всегда лучше использовать стандартные методы, чтобы получить расширение файла. Если вы уже используете модуль os, используйте метод splitext(). Для объектно-ориентированного подхода используйте модуль pathlib.
Получение размера файла
Мы можем получить размер файла в Python, используя модуль os.
Модуль os имеет функцию stat(), где мы можем передать имя файла в качестве аргумента. Эта функция возвращает структуру кортежа, содержащую информацию о файле. Затем мы можем получить его свойство st_size, чтобы получить размер файла в байтах.
Вот простая программа для печати размера файла в байтах и мегабайтах.

Если вы посмотрите на функцию stat(), мы можем передать еще два аргумента: dir_fd и follow_symlinks. Однако они не реализованы для Mac OS.
Вот обновленная программа, в которой я пытаюсь использовать относительный путь, но выдает NotImplementedError.
Python: Get file size in KB, MB or GB – human-readable format
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()
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.
Let’s use this function to get the size of a file in bytes,
Get file size in bytes using os.stat().st_size
Python’s os module provides a function to get the file statistics,
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.
Read More:
Let’s use this function to get the size of a file in bytes,
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,
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.
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,
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
Get size of a file in Megabyte i.e. MB
Get size of a file in Gigabyte i.e. 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,
As file ‘dummy_file.txt’ does not exist, so we can not calculate its size.
The complete example is as follows,
Output:
Related posts:
Advertisements
Thanks for reading.
2 thoughts on “Python: Get file size in KB, MB or GB – human-readable format”
Hi, I updated one of your function in a more convenient way. The size_unit doesn’t have to be passed as parameter.
class SIZE_UNIT(Enum):
“””Enumeration of computer size units.”””
BYTES = 1
KB = 2
MB = 3
GB = 4
TB = 5
def get_file_size(file_path) -> (float,str):
“””Get file in size in given unit like KB, MB or GB”””
size = os.path.getsize(file_path)
for unit in SIZE_UNIT:
byte_value = 1024**(unit.value-1)
if size > byte_value:
formated_size = size/(byte_value)
size_unit = unit
return round(formated_size,2), size_unit.name
The unit conversion can be greatly simplified by taking advantage of enum name and value attributes e.g.
“`python
class SIZE_UNIT(enum.Enum):
BYTES = 1
KB = 1024
MB = 1024 * 1024
GB = 1024 * 1024 * 1024
def convert_unit(size_in_bytes:int, unit:SIZE_UNIT) -> float:
return size_in_bytes / unit.value
“`
Then use the function to convert to MB like so: `convert_unit(value, SIZE_UNIT.MB)`
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Advertisements
Advertisements
Advertisements
Advertisements
| Python Basics |
|---|
| Python – Keywords and Identifiers |
| Python – Variables |
| Python – Literals |
| Loops in Python |
| Python- While Loop |
| Python- For Loop |
| Python- break keyword in loops |
| Python – continue keyword in loops |
| Python Conditions |
| Python – if-statement |
| Python – if…else statement |
| Python – if…elif…else statement |
| Python- Ternary operator |
| Python Functions |
| Python Functions |
| Global variables in a function |
| Variable number of arguments in function |
| Python Lists |
| What is a List & why we need it |
| Create & initialise a List |
| Check if List contains an item |
| Add / append an element in list |
| Update values in a List |
| Remove an element from List |
| Python Dictionaries |
| Introduction to Dictionaries |
| Creating Dictionaries |
| Add key value pairs in dictionary |
| Iterate / Loop over a Dictionary |
| Filter a dictionary by conditions |
| Python Strings |
| Accessing characters in a string |
| Check if string has a substring |
| Iterate over the string characters |
| Find occurrence a substring |
| Compare strings in Python |
| Remove characters from a string |
| Python Tuples |
| Create a Tuple and Iterate over it |
| Find an element in Tuple by value |
| Add, update & delete in tuple |
| Python Iterators |
| Iterator vs Iterable vs Iteration |
| Make a class Iterable |
| Yield Keyword & Generators |
| Iterators vs Generators |
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
How do I check file size in Python?
![]()
You need the st_size property of the object returned by os.stat . You can get it by either using pathlib (Python 3.4+):
Output is in bytes.
The other answers work for real files, but if you need something that works for «file-like objects», try this:
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!)
Python Check File Size
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
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 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
Output:
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.
Output:
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:
Output:
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:
Output:
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. The tell() 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:
Output:
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.
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.