首页 > 编程知识 正文

python读取文件字节大小,python如何读取大文件

时间:2023-05-05 11:07:09 阅读:261225 作者:985

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 pythonimport osfile_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

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 pythonimport osfile_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文件大小相对路径NotImplementedError

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

python中获取文件大小

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。