Python file size in bytes

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:

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

Источник

How to Get File Size in Python in Bytes, KB, MB, and GB

How to Get File Size in Python in Bytes, KB, MB, and GB Cover Image

When working with files programmatically, you’ll often want to know how large a file is. This can be helpful when transferring files or copying files. Python provides a number of built-in methods of doing this, including using the os and pathlib libraries. Depending on your preference, either of these approaches works well.

By the end of this tutorial, you’ll have learned:

  • How to get the file size in Python using os and pathlib
  • How to get the file size in Python in bytes, KB, MB, and GB

How to Use Python os to Get a File Size

The Python os library provides two different ways to get the size of a file: the os.path.getsize() function and the os.stat() function. The getsize() function, as the name implies, returns the size of the file. On the other hand, the stat() function returns a number of statistics, or attributes, about the file.

Let’s see how both of these functions can be used to use Python to get a file size.

How to Use os.path.getsize() to Get File Size

In this section, you’ll learn how to use the getsize function to get the size of a file. The function accepts a file path pointing to the file and returns the size in bytes. Let’s see how we can use the function to get the file size:

# Get the Size of a File Using getsize() import os file_path = '/Users/datagy/Desktop/file.py' print(os.path.getsize(file_path)) # Returns: 2453

In the example above, we use the getsize function and pass in a string containing the path to a file. If the file doesn’t exist, Python will raise a PermissionError , indicating that no file could be found.

One of the benefits of the function is how explicit it is. It lets the user know immediately that you’re hoping to get the size of a file.

How to Use os.stat() to Get File Size

The Python os stat function returns a stat_result object which provides information about the file itself. Included in this are items such as the size and owner information.

# Get Size of a File Using os.stat() import os file_path = '/Users/datagy/Desktop/file.py' print(os.stat(file_path)) # Returns: os.stat_result(st_mode=33188, st_ino=69380148, st_dev=16777233, st_nlink=1, st_uid=501, st_gid=20, st_size=2453, st_atime=1665780677, st_mtime=1662640208, st_ctime=1665780674)

We can then access the size of the file by accessing the .st_size attribute. Let’s see how we can do this with Python:

# Get Size of a File Using os.stat() import os file_path = '/Users/datagy/Desktop/file.py' print(os.stat(file_path.st_size)) # Returns: st_size=2453

In the code block above, we can see that by accessing the .st_size attribute, the size is returned in bytes. The function returns an item that’s like a NamedTuple – where we can access items based on their named attributes. This is shown below:

# Checking the Type of an os.stat object import os file_path = '/Users/datagy/Desktop/file.py' print(type(os.stat(file_path))) # Returns:

In the code block above, we access the type of the returned value, which is like a NamedTuple.

How to Use Python Pathlib to Get a File Size

The Python Pathlib library also allows you to access information about files, including the size of a file. The Pathlib library provides an object-oriented interface for working with files. In order to access the size of a file, we can use the .stat() method and access the .st_size attribute. Let’s see what this looks like:

# Using Pathlib to Get the Size of a File in Python import pathlib file_path = '/Users/datagy/Desktop/file.py' path = pathlib.Path(file_path) print(path.stat().st_size) # Returns: 2453

In order to get the size of a file in Python using the pathlib library, you can:

  1. Import the pathlib library Because the library is built into Python, you don’t need to install it first
  2. Create a path object by instantiating a Path() object The pathlib Path object can be created using pathlib.Path()
  3. Access the size using the .stat().st_size attribute By applying the .stat() method and accessing the .st_size attribute, you can access the size of a file in bytes.

How to Use Python to Get the File Size in KB, MB, or GB

All the methods covered in this tutorial return the size of a file in bytes. However, we can easily get the size of a file in Python in KB, MB, and GB using a custom function. In order to do this, let’s write a function that allows you to pass in a file path and the format you want to return the size in.

# Getting the Size of a File in Python Using Different Units import os file_path = '/Users/datagy/Desktop/LargeFile.MOV' def get_size(file_path, unit='bytes'): file_size = os.path.getsize(file_path) exponents_map = if unit not in exponents_map: raise ValueError("Must select from \ ['bytes', 'kb', 'mb', 'gb']") else: size = file_size / 1024 ** exponents_map[unit] return round(size, 3) print(get_size(file_path, 'mb')) # Returns: 104.062

Let’s break down what the code block above is doing:

  1. We import the os library and instantiate our file_path variable
  2. We then create a function get_size() which takes two parameters
  3. The function first gets the size in bytes
  4. It then creates a mapping object that maps units to an exponent
  5. The function then first checks if the unit is available to be calculated. If not, it raises a ValueError.
  6. Finally, the function returns the file size divided by 1024 raised to the power of the unit

Conclusion

In this tutorial, you learned how to use Python to get the size of a file. You first learned how to use the os library to explore two different methods of getting the size of a file. Then, you learned how to use the Python pathlib library to get the size of a file. Finally, you learned how to use these methods to convert the sizes of files to KB, MB, and GB.

Additional Resources

To learn more about related topics, check out the tutorials below:

Источник

How to Get File Size in Python

How to Get File Size in Python

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

File Size in Python

The python os module has stat() function where we can pass the file name as argument. This function returns a tuple structure that contains the file information. We can then get its st_size property to get the file size in bytes. Here is a simple program to print the file size in bytes and megabytes.

# get file size in python import os file_name = "/Users/pankaj/abcdef.txt" file_stats = os.stat(file_name) print(file_stats) print(f'File Size in Bytes is ') print(f'File Size in MegaBytes is ') 

File Size In Python

Output: If you look at the stat() function, we can pass two more arguments: dir_fd and follow_symlinks. However, they are not implemented for Mac OS. Here is an updated program where I am trying to use the relative path but it’s throwing NotImplementedError.

# get file size in python import os file_name = "abcdef.txt" relative_path = os.open("/Users/pankaj", os.O_RDONLY) file_stats = os.stat(file_name, dir_fd=relative_path) 
Traceback (most recent call last): File "/Users/pankaj/. /get_file_size.py", line 7, in file_stats = os.stat(file_name, dir_fd=relative_path) NotImplementedError: dir_fd unavailable on this platform 

Python File Size Relative Path NotImplementedError

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

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