Get file size in python _how to get file size in python

get file size in python

We can get file size in Python using the os module.

We can get the file size in Python using the os module .

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.

The python os module has the stat() function where we can pass the filename as an argument. The function returns a tuple structure containing file information. Then, we can get itsst_sizeproperty to get the file size in bytes.

Here is a simple program to print the file size in bytes and megabytes.

Here is a simple program that prints the file size in bytes and megabytes.

  1. # get file size in python
  2. import them
  3. file_name = "/Users/pankaj/abcdef.txt"
  4. file_stats = os.stat(file_name)
  5. print(file_stats)
  6. print(f'File Size in Bytes is {file_stats.st_size}')
  7. print(f'File Size in MegaBytes is {file_stats.st_size / (1024 * 1024)}')

Output:

output :

File Size In Python

File Size In Python

File size in Python

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.

If you look at the stat() function, we can pass two more parameters: dir_fd and follow_symlinks. However, they are not implemented in Mac OS.

Here is an updated program where I am trying to use the relative path but it’s throwing NotImplementedError.

Here's an updated program, I tried using relative paths, but it throws NotImplementedError.

  1. # get file size in python
  2. import them
  3. file_name = "abcdef.txt"
  4. relative_path = os.open("/Users/pankaj", os.O_RDONLY)
  5. file_stats = os.stat(file_name, dir_fd=relative_path)

Output:

output:

  1. Traceback (most recent call last):
  2. File "/Users/pankaj/.../get_file_size.py", line 7, in
  3. file_stats = os.stat(file_name, dir_fd=relative_path)
  4. NotImplementedError: dir_fd unavailable on this platform
Python File Size Relative Path NotImplementedError

Python File Size Relative Path NotImplementedError

Python file size relative path NotImplementedError

Translated from: https://www.journaldev.com/32067/how-to-get-file-size-in-python

get file size in python

Related: Get file size in python _how to get file size in python