{"id":10541,"date":"2021-12-29T15:28:57","date_gmt":"2021-12-29T09:58:57","guid":{"rendered":"https:\/\/pynative.com\/?p=10541"},"modified":"2021-12-29T15:31:54","modified_gmt":"2021-12-29T10:01:54","slug":"python-get-file-size","status":"publish","type":"post","link":"https:\/\/pynative.com\/python-get-file-size\/","title":{"rendered":"Python Check File Size"},"content":{"rendered":"\n
In this tutorial, you\u2019ll learn how to get file size in Python.<\/p>\n\n\n\n
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.<\/p>\n\n\n\n
In this article, We will use the following three methods<\/strong> of an OS and pathlib module to get file size.<\/p>\n\n\n\n os.path module<\/strong>:<\/p>\n\n\n\n Pathlib module<\/strong>:<\/p>\n\n\n\n For example, you want to\u00a0read a file<\/a>\u00a0to analyze the sales data to prepare a monthly report, but before performing this operation we want to check whether the file contains any data. This module helps us to work with file paths and directories in Python. Using this module, we can access and manipulate paths<\/p> <\/li> A file path defines the location of a file or folder in the computer system. There are two ways to specify a file path. Use the os.path.getsize('file_path')<\/code>: Return the file size in bytes.<\/li>
os.stat(file).st_size<\/code>: Return the file size in bytes<\/li><\/ul>\n\n\n\n
pathlib.Path('path').stat().st_size<\/code>: Return the file size in bytes.<\/li><\/ul>\n\n\n\n
os.path.getsize() Method to Check File Size<\/h2>\n\n\n\n
The\u00a0os.path module<\/a>\u00a0has some valuable functions on pathnames. Here we will see how to use the\u00a0os.path<\/code>\u00a0module to check the file size.<\/p>
Absolute path<\/strong><\/em>: which always begins with the root folder. The absolute path includes the complete directory list required to locate the file. For example,\u00a0\/user\/Pynative\/data\/sales.txt<\/code>\u00a0is 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<\/em><\/strong>: which is relative to the program\u2019s current working directory.
To maintain uniformity across the operating system,\u00a0use the forward-slash<\/em>\u00a0(\/<\/code>) to separate the path. It\u2019ll work across Windows, macOS, and Unix-based systems, including Linux.<\/p> <\/li>
os.path.getsize('file_path')<\/code> 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<\/strong>. It raises OSError<\/strong> if the file does not exist or is inaccessible.<\/p> <\/li><\/ol><\/div>\n\n\n\n
Example To Get File Size<\/h3>\n\n\n