Найти размер файла python

3 способа получить размер файла в Python

Python stat() — это встроенный модуль OS , который имеет два метода, которые возвращают размер файла. Модуль OS в Python предоставляет функции для взаимодействия с операционной системой. Он входит в стандартные служебные модули Python. Модуль os обеспечивает портативный подход к использованию функций, зависящих от операционной системы.

Получение размера файла в Python

Чтобы получить размер файла в Python, мы можем использовать один из следующих трех способов:

Как получить размер файла в Python

Python os.path.getsize()

Функция os.path.getsize() возвращает размер в байтах. Вызовет OSError, если файл не существует или недоступен.

Сначала мы определили файл, а затем получили его размер с помощью функции os.path.getsize(), которая возвращает размер файла в байтах, а затем в последней строке мы преобразовали размер в байтах в размер в МБ.

Python os.stat()

Метод os.stat() в Python выполняет системный вызов stat() по указанному пути. Метод stat() используется для получения статуса указанного пути. Затем мы можем получить его атрибут st_size, чтобы получить размер файла в байтах. Метод stat() принимает в качестве аргумента имя файла и возвращает кортеж, содержащий информацию о файле.

Из вывода вы можете видеть, что мы получили кортеж, полный информации о файле. Затем мы получили доступ к определенному свойству, называемому st_size, чтобы получить размер файла, а затем преобразовать размер в МБ или мегабайты.

Если вы внимательно посмотрите на метод stat(), мы можем передать еще два параметра: dir_fd и follow_symlinks. Однако они не реализованы для macOS.

Python path.stat().st_mode

Функция Python path.stat() возвращает объект os.stat_result, содержащий информацию об этом пути, подобно os.stat(). Результат просматривается при каждом вызове этого метода.

Источник

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.

Читайте также:  Common exception types in java

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:

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.

  1. 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
  2. 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.

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 size is', sz, 'bytes')
E:/demos/account/sales.txt size is 10560 bytes

Get File Size in KB, MB, or GB

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)

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 .

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')

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
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)

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.
# 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)

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:

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

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

Источник

Получить размер файла в Python

В этом посте мы обсудим, как получить размер файла в Python.

1. Использование os.stat() функция

Стандартным решением для получения статуса файла является использование os.stat() Функция Python. Он возвращает stat_result объект, который имеет st_size атрибут, содержащий размер файла в байтах.

2. Использование Path.stat() функция

В качестве альтернативы с Python 3.4 вы можете использовать Path.stat() функция от pathlib модуль. Это похоже на os.stat() функция и возвращает stat_result объект, содержащий информацию об указанном пути.

3. Использование os.path.getsize() функция

Еще один хороший вариант — использовать os.path.getsize() функция для получения размера указанного пути в байтах.

4. Использование seek() функция

Здесь идея состоит в том, чтобы открыть файл в режиме только для чтения и установить в конце текущую позицию файлового дескриптора. Это можно сделать с помощью seek() функция, которая возвращает текущую позицию курсора в байтах, начиная с начала.

Это все, что касается получения размера файла в Python.

Средний рейтинг 4.79 /5. Подсчет голосов: 29

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно

Источник

Оцените статью