How to Get the Size of a File in Python
Created
Modified
Using os.path.getsize Method
The os.path.getsize()
method returns the size, in bytes, of path. Raise OSError if the file does not exist or is inaccessible. For example,
#!/usr/bin/python3
# Import module
import os
size = os.path.getsize("file.txt")
print(size)
10259
Note: the implementation of os.path.getsize is simply return os.stat(filename).st_size.
Using pathlib Module
You can use pathlib.Path().stat() function, it really simple. For example,
#!/usr/bin/python3
# Python 3.4+
# Import module
import pathlib
stat = pathlib.Path("file.txt").stat()
print(stat.st_size)
10259
Using os.stat Method
The os.stat()
method gets the status of a file or a file descriptor.
For example,
#!/usr/bin/python3
# Import module
import os
stat = os.stat("file.txt")
print(stat.st_size)
10259