Python

Python Get File Size from System

In Python, there are several methods for determining the size of a file. There appear to be methods for effectively obtaining the size of a file object by importing the file into Python and methods for obtaining the size of a file object via os calls via your file system. Your specific requirements will choose your preferred method. You’ll learn how to retrieve file size in Python in this tutorial.

Before executing each function on a file, we must occasionally check the file size. For example, if you’re trying to replicate data from one file to another. Before conducting the file copying process, we can check if the file size is more than 0. We’ll use three methods in this article: the os.path module, the stat function, and the file object. In Python, you can obtain the file size in just about any way you wish. It’s critical to retrieve the file size in Python to monitor the size of the file or sort files in a directory by file size.

Example 1:

The first method of determining the file’s size is to use os.path.getsize(). The os module is also involved. This module allows us to work with file paths and directories in Python. We can access and modify paths using this module. In comparison to os.stat(file).st size, the implementation of os.path.getsize() is simple and straightforward .It raises an os.error if the file somehow doesn’t exist or is unavailable. The getsize function in Python’s os.path module accepts a file path as an input and returns the file’s size in bytes. In this case, we must specify the precise file path (absolute path), not a relative path.

The root folder is always at the start of an absolute path. The absolute path contains the entire directory list needed to find the file. /user/mydocuments/data/abc.txt, for example, is an absolute path to the abc.txt file. The path string contains all of the information required to get the file. The relative is known to contribute to the program’s current working directory. As you can see, we used the getsize function to get the exact size of the file after importing the os module. After that, we printed the outcome.

import os

s = os.path.getsize('D:/demo.txt')

print('File size:', s, 'bytes')

https://lh5.googleusercontent.com/aMZYigBNIMh7nsjEol9koIJFNHtqCmiQxpSVIPlTBcKY_tA7wkeGPpHj0oUAspGtpRY8QLaQ1JcAKBIXmjF1nlHIVFQiJdwY49umtgoAvUHnKccW8zGwd8SJaH8BVUoDinkqG69S

The outcome of the code above is as follows.

https://lh6.googleusercontent.com/Md5rfGRs3ftHkJ1SpdkKsjnWy2nm5QlPJ8Nq1vcVnq8XqSgU8qSZ1OqVIyzVtDF5sfqSAZrHnDVypZyzneWyCfl-epPA72zHakM2kSTE6LntuLKNa82b4kbzUIM6eFkjhHca9htJ

Example 2:

The os.stat() method returns an object containing numerous file system descriptors of the file, such as its size, last updated time, user identification, etc. It is beneficial to use this method to learn more about a file. os.stat() is a function similar to os.path. The sole argument to getsize() is the file path. The os module in Python has a stat method that accepts a path as an argument. This path can be a string or just a path object, and it returns a structure with statistical information about the journey. Among the various characteristics of this structure, the st_size field contains the size of a file present at the specified path.

import os

s = os.stat('D:/demo.txt')

print('File size:', s.st_size, 'bytes')

https://lh6.googleusercontent.com/cU41qa2DOOoBdFCySO2m13-lpNVLx5V4x3vRd1t1eCtcITdjsUUJ3rTjGrfGEt0moo4ponJf8TiwZ5Ti7RyrkD_ou2aJl_NV4Zay5HkT2Mxsy8W70g6B1h94bRYA1zOtopokda3J

The following is the code’s output.

https://lh6.googleusercontent.com/6y7DB8FFSsWY2MUAsyA9d6bVwc67yCEy_LTum3Jzh3llvHHz8jsMZPp07a0NT7BbF9y9hNWyGBjLCJqhs0jnKut59v1j7OXdpaHTNjBaihAbv5vyogrjdFI27pM80L02QbWbNO_K

Example 3:

A more reliable technique of obtaining a file’s size in Python is to open the file as either a file object, search to the end of the file, and read the cursor’s location at the end of the file, which will be equal to the size of the in bytes. In Python, this function helps determine the size of a huge file object in real-time. Once we have the object pointing to the file, we must conduct the steps below to get the file size to use this method. When a file is first opened, the file cursor refers to the beginning of the file.

The seek method on the File object is used to move the cursor to a certain location. It takes two arguments, the first of which is the cursor’s start location, and the second of which is the cursor’s end location. If the first parameter is missing, the value sets to 0 by default, which means the file starts at the beginning. Use the seek method to move the cursor to the end of the file, with 0 as the start value and os as the destination. SEEK END is the end value, where SEEK END is an os module constant that indicates the file’s end.

import os

a = open('D:/demo.txt')

a.seek(0, os.SEEK_END)

print('File size:', a.tell(), 'bytes')

https://lh5.googleusercontent.com/Lta6tc77Am_PxLaCvvy2hTuIYbHTqhXLaLJAKCKJrUpshGGNP0gSX0Ziwu99aDjRle6M7GoMGC2R__0X1b_XQkKjM_OXA2yc8x4so5ZR0xT_dlf3KJqtE5-Ie402zQXtOwck9z68

The file size can be seen below.

https://lh5.googleusercontent.com/RRZ7bnU7h9UZxnGgaDioxCCjts6l9ezf8Om0zmvjZ2MDM82pextzIAN1r36kldCK7D8KBy3ILDpI5cMFkH9Er9Gssq6H7NDaJpYOP9B7_L2VEiye0UHCMMIUlHvE0wQbvPQL1x8z

Conclusion:

We now understand why it is critical to obtain file size in Python when ranking files by size or in various other scenarios. The file size output is always in bytes. The value might be supplied in multiples of the file system block size to make future computation easier. We learned how to inspect the file size using multiple built-in functions like seek(), tell(), st_size(), and os.path.getsize() in this post. We also employed some unique programming and file management concepts. We used the open() method to open the file, and then we utilized functions to check the file size.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content