Hướng dẫn get file size python - lấy kích thước tệp python

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

Nội dung chính Show

  • File Size in Python
  • Want to learn more? Join the DigitalOcean Community!
  • Lấy kích thước file trong ptyhon | os.path.getsize()
  • Lấy kích thước thư mục trong python | os.scandir()
  • Lấy kích thước thư mục trong python | os.isdir()
  • Tổng kết và thực hành

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

# get file size in python
import os

file_name = "abcdef.txt"
relative_path = os.open("/Users/pankaj", os.O_RDONLY)

file_stats = os.stat(file_name, dir_fd=relative_path)
4 property to get the file size in bytes. Here is a simple program to print the file size in bytes and megabytes.

# get file size in python
import os

file_name = "/Users/pankaj/abcdef.txt"

file_stats = os.stat(file_name)

print(file_stats)
print(f'File Size in Bytes is {file_stats.st_size}')
print(f'File Size in MegaBytes is {file_stats.st_size / (1024 * 1024)}')

Output:::

Hướng dẫn get file size python - lấy kích thước tệp 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. Here is an updated program where I am trying to use the relative path but it’s throwing NotImplementedError.

# get file size in python
import os

file_name = "abcdef.txt"
relative_path = os.open("/Users/pankaj", os.O_RDONLY)

file_stats = os.stat(file_name, dir_fd=relative_path)

Output:

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

Python File Size Relative Path NotImplementedError

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up

Hướng dẫn cách lấy kích thước file và thư mục trong python. Bạn sẽ học được cách lấy kích thước file trong python bằng hàm os.path.getsize() cũng như kết hợp với các hàm os.scandir() và os.listdir() để lấy kích thước thư mục trong python sau bài học này.lấy kích thước file và thư mục trong python. Bạn sẽ học được cách lấy kích thước file trong python bằng hàm os.path.getsize() cũng như kết hợp với các hàm os.scandir() và os.listdir() để lấy kích thước thư mục trong python sau bài học này.

Lấy kích thước file trong ptyhon | os.path.getsize()

Để lấy kích thước một file đã tồn tại trong ptyhon, chúng ta sử dụng hàm os.path.getsize() trong module os, với cú pháp sau đây:

os.path.getsize(path)

Trong đó

# get file size in python
import os

file_name = "abcdef.txt"
relative_path = os.open("/Users/pankaj", os.O_RDONLY)

file_stats = os.stat(file_name, dir_fd=relative_path)
0 là đường dẫn của file cần lấy kích thước. Kết quả trả về sẽ là kích thước file với đơn vị
# get file size in python
import os

file_name = "abcdef.txt"
relative_path = os.open("/Users/pankaj", os.O_RDONLY)

file_stats = os.stat(file_name, dir_fd=relative_path)
1 như sau:
import os

filesize=os.path.getsize('data/kiyoshi.png')
print(filesize,"KB")

Để lấy kết quả kích thước file với đơn vị khác, ví dụ như là GB, chúng ta chia kết quả với hệ số là xong.

import os
gb = 1024 ** 3
filesize_gb=round(os.path.getsize('data/kiyoshi.png')/gb,4)
print(filesize_gb,"GB")

Nếu file đó không tồn tại hoặc không thể truy cập, lỗi OSError sẽ xảy ra:

OSError: File not found

Lấy kích thước thư mục trong python | os.scandir()

Ứng dụng hàm os.path.getsize() và kết hợp với hàm os.scandir(), chúng ta có thể lấy kích thước thư mục trong python bằng cách tính tổng kích thước tất cả các file có trong thư mục đó, với chương trình sau đây:

import os
def get_dir_size(path='.'):
total = 0
with os.scandir(path) as it:
for entry in it:
if entry.is_file():
total += entry.stat().st_size
elif entry.is_dir():
total += get_dir_size(entry.path)
return total

print(get_dir_size('data/src'))

Trong mã mẫu, chúng ta tạo ra một trình lặp (Iterator) từ hàm os.scandir(), sau đó với mỗi đường dẫn

# get file size in python
import os

file_name = "abcdef.txt"
relative_path = os.open("/Users/pankaj", os.O_RDONLY)

file_stats = os.stat(file_name, dir_fd=relative_path)
2 lấy ra từ trình lặp, chúng ta sẽ kiểm tra đó là file hay thư mục con, và tùy vào đó để tiến hành lấy thuộc tính
# get file size in python
import os

file_name = "abcdef.txt"
relative_path = os.open("/Users/pankaj", os.O_RDONLY)

file_stats = os.stat(file_name, dir_fd=relative_path)
3 - kích thước của file để cộng vào biến tổng kích thước
# get file size in python
import os

file_name = "abcdef.txt"
relative_path = os.open("/Users/pankaj", os.O_RDONLY)

file_stats = os.stat(file_name, dir_fd=relative_path)
4.

Nếu như bạn chỉ muốn lấy tổng kích thước các file nằm trực tiếp dưới thư mục đó mà không lấy tất cả các file trong thư mục con một cách đệ quy, hãy xóa dòng code dưới đây trong mã lệnh là xong:

# get file size in python
import os

file_name = "abcdef.txt"
relative_path = os.open("/Users/pankaj", os.O_RDONLY)

file_stats = os.stat(file_name, dir_fd=relative_path)
2
  • Bạn có thể tìm hiểu thêm về cách sử dụng hàm os.scandir() tại bài Lấy thông tin file trong python

Lấy kích thước thư mục trong python | os.isdir()

Trong các phiên bản Python3.4 về trước, do không tồn tại hàm os.scandir() nên chúng ta phải dùng kết hợp hàm os.isdir() để lấy kích thước thư mục, với mã lệnh sau đay:

# get file size in python
import os

file_name = "abcdef.txt"
relative_path = os.open("/Users/pankaj", os.O_RDONLY)

file_stats = os.stat(file_name, dir_fd=relative_path)
3

Cách sử dụng thì tương tự như với ở phần trên, và bạn có thể chọn một trong hai kiểu để lấy kích thước thư mục trong python. Tuy nhiên cách dùng os.scandir() thì mới hơn nên nó có thể có nhiều ưu điểm hơn với cách sử dụng cũ, nên Kiyoshi khuyên bạn nên dùng hàm os.scandir() hơn khi muốn lấy kích thước thư mục trong python.lấy kích thước thư mục trong python. Tuy nhiên cách dùng os.scandir() thì mới hơn nên nó có thể có nhiều ưu điểm hơn với cách sử dụng cũ, nên Kiyoshi khuyên bạn nên dùng hàm os.scandir() hơn khi muốn lấy kích thước thư mục trong python.

Tổng kết và thực hành

Trên đây Kiyoshi đã hướng dẫn bạn về cách lấy kích thước file và thư mục trong python rồi. Để nắm rõ nội dung bài học hơn, bạn hãy thực hành viết lại các ví dụ của ngày hôm nay nhé.lấy kích thước file và thư mục trong python rồi. Để nắm rõ nội dung bài học hơn, bạn hãy thực hành viết lại các ví dụ của ngày hôm nay nhé.

Và hãy cùng tìm hiểu những kiến thức sâu hơn về python trong các bài học tiếp theo.

Viết bởi Kiyoshi. Đã đăng ký bản quyền tác giả tại Creativecommons và DMCA