The path.getsize method of the os module

The path.getsize method returns the size in bytes of a file or folder. In the method parameter, we specify the path to the desired file or folder. If the specified path does not exist, then the OSError exception is returned.

Syntax

pythonimport os

print(os.path.getsize(path))

Example

Let's find out the size of our file in bytes:

pythonimport os

print(os.path.getsize('file.txt'))

The result of the executed code:

python210

Example

Let's find out the file size in kilobytes. To do this, simply divide the obtained value by 1000:

pythonimport os

print(os.path.getsize('file.txt') / 1000)

The result of the executed code:

python0.21

See also

  • method disk_usage of module shutil,
    which returns disk usage statistics
  • method stat of module os,
    which returns the status of the path
  • method path.exists of module os,
    which checks the existence of a path
  • method path.isdir of module os,
    which checks the existence of a folder
  • method path.isfile of module os,
    which checks the existence of a file