python中获取文件大小_如何在Python中获取文件大小

python中获取文件大小

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

我们可以使用os模块在Python中获取文件大小。

Python中的文件大小 (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.

python os模块具有stat()函数,我们可以在其中传递文件名作为参数。 该函数返回一个包含文件信息的元组结构。 然后,我们可以获取其st_size属性以获取文件大小(以字节为单位)。

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:

输出

File Size In Python

File Size In Python

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.

如果您查看stat()函数,我们可以再传递两个参数:dir_fd和follow_symlinks。 但是,它们未在Mac OS中实现。

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

这是一个更新的程序,我尝试使用相对路径,但是会抛出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

Python File Size Relative Path NotImplementedError

Python文件大小相对路径NotImplementedError

翻译自: https://www.journaldev.com/32067/how-to-get-file-size-in-python

python中获取文件大小

  • 4
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值