linux下如何用python文件大小

Linux下用Python获取文件大小,可使用os.path.

Linux下使用Python获取文件大小是一个常见的操作,通常可以通过标准库中的os模块和os.path子模块来实现,以下是详细的步骤和示例代码,帮助你了解如何在Linux环境下使用Python来获取文件的大小。

使用 os.path.getsize() 方法

os.path.getsize() 是获取文件大小的最简单方法,它接受一个文件路径作为参数,并返回文件的大小(以字节为单位),如果文件不存在,会抛出 FileNotFoundError 异常。

示例代码:

import os
def get_file_size(file_path):
    try:
        size = os.path.getsize(file_path)
        return size
    except FileNotFoundError:
        print(f"文件 {file_path} 不存在。")
        return None
# 示例用法
file_path = '/path/to/your/file'
size = get_file_size(file_path)
if size is not None:
    print(f"文件大小: {size} 字节")

使用 os.stat() 方法

os.stat() 方法返回一个包含文件详细信息的对象,包括文件大小、修改时间等,你可以通过访问 st_size 属性来获取文件大小。

示例代码:

import os
def get_file_size(file_path):
    try:
        stat_info = os.stat(file_path)
        size = stat_info.st_size
        return size
    except FileNotFoundError:
        print(f"文件 {file_path} 不存在。")
        return None
# 示例用法
file_path = '/path/to/your/file'
size = get_file_size(file_path)
if size is not None:
    print(f"文件大小: {size} 字节")

使用 pathlib 模块

pathlib 是Python 3.4引入的一个模块,提供了面向对象的文件系统路径操作,你可以使用 Path 对象的 stat() 方法来获取文件大小。

示例代码:

from pathlib import Path
def get_file_size(file_path):
    path = Path(file_path)
    if path.exists():
        size = path.stat().st_size
        return size
    else:
        print(f"文件 {file_path} 不存在。")
        return None
# 示例用法
file_path = '/path/to/your/file'
size = get_file_size(file_path)
if size is not None:
    print(f"文件大小: {size} 字节")

处理大文件和目录

如果你需要获取目录中所有文件的总大小,或者处理非常大的文件,可以使用以下方法:

获取目录中所有文件的总大小:

import os
def get_directory_size(directory_path):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(directory_path):
        for file in filenames:
            file_path = os.path.join(dirpath, file)
            try:
                total_size += os.path.getsize(file_path)
            except FileNotFoundError:
                pass
    return total_size
# 示例用法
directory_path = '/path/to/your/directory'
total_size = get_directory_size(directory_path)
print(f"目录总大小: {total_size} 字节")

处理大文件:

对于非常大的文件,直接读取整个文件可能会消耗大量内存,可以使用逐块读取的方式来计算文件大小。

def get_large_file_size(file_path):
    block_size = 65536  # 64KB
    total_size = 0
    with open(file_path, 'rb') as f:
        while True:
            block = f.read(block_size)
            if not block:
                break
            total_size += len(block)
    return total_size
# 示例用法
file_path = '/path/to/your/large/file'
size = get_large_file_size(file_path)
print(f"大文件大小: {size} 字节")

格式化文件大小输出

文件大小以字节为单位显示,但为了更易读,可以将其转换为更友好的单位(如KB、MB、GB等)。

示例代码:

def format_size(size):
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if size < 1024:
            return f"{size:.2f} {unit}"
        size /= 1024
    return f"{size:.2f} PB"
# 示例用法
size = 123456789
formatted_size = format_size(size)
print(f"格式化后的文件大小: {formatted_size}")

完整示例:获取文件大小并格式化输出

import os
def get_file_size(file_path):
    try:
        size = os.path.getsize(file_path)
        return size
    except FileNotFoundError:
        print(f"文件 {file_path} 不存在。")
        return None
def format_size(size):
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if size < 1024:
            return f"{size:.2f} {unit}"
        size /= 1024
    return f"{size:.2f} PB"
# 示例用法
file_path = '/path/to/your/file'
size = get_file_size(file_path)
if size is not None:
    formatted_size = format_size(size)
    print(f"文件大小: {formatted_size}")

相关问答FAQs

问题1:如何获取目录下所有文件的总大小?

解答: 你可以使用 os.walk() 函数遍历目录中的所有文件,并累加每个文件的大小,以下是一个示例代码:

import os
def get_directory_size(directory_path):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(directory_path):
        for file in filenames:
            file_path = os.path.join(dirpath, file)
            try:
                total_size += os.path.getsize(file_path)
            except FileNotFoundError:
                pass
    return total_size
# 示例用法
directory_path = '/path/to/your/directory'
total_size = get_directory_size(directory_path)
print(f"目录总大小: {total_size} 字节")

问题2:如何处理非常大的文件以避免内存不足?

解答: 对于非常大的文件,直接读取整个文件可能会消耗大量内存,你可以逐块读取文件来计算其大小,以下是一个示例代码:

def get_large_file_size(file_path):
    block_size = 65536  # 64KB
    total_size = 0
    with open(file_path, 'rb') as f:
        while True:
            block = f.read(block_size)
            if not block:
                break
            total_size += len(block)
    return total_size
# 示例用法
file_path = '/path/to/your/large/file'
size = get_large_file_size(file_path)
print(f"大文件大小: {size} 字节")

小伙伴们,上文介绍linux下如何用python文件大小的内容,你了解清楚吗?希望对你有所帮助,任何问题可以给我留言,让我们下期再见吧。

原创文章,发布者:酷番叔,转转请注明出处:https://cloud.kd.cn/ask/11186.html

(0)
酷番叔酷番叔
上一篇 2025年8月15日 21:11
下一篇 2025年8月15日 21:18

相关推荐

  • 如何linux挂载共享

    Linux 中,可使用 mount 命令结合相关参数来挂载共享资源,如网络

    2025年8月15日
    7100
  • Linux如何查看设备的设备号及详细信息?

    在Linux系统中,设备号是内核用于标识和管理硬件设备的唯一标识符,由主设备号(Major Number)和次设备号(Minor Number)组成,主设备号用于标识设备类型(如磁盘、终端等),对应设备的驱动程序;次设备号用于区分同一类型下的不同设备实例(如不同磁盘分区、多个串口等),查看设备号是系统管理和驱动……

    2025年8月30日
    7300
  • Linux听音频全场景开源方案?

    Linux系统提供多种收听音频方式,包括本地文件、在线流媒体和播客,推荐的开源工具安全易获取,适合从新手到高级用户的不同需求。

    2025年8月8日
    9300
  • aws linux如何连接

    SSH客户端,使用实例的公有DNS和相应密钥或密码,可连接AWS Linux

    2025年8月18日
    8600
  • 怎样设置桌面环境?

    在Linux系统中,跳过密码登录通常指自动登录(Auto Login)功能,允许用户无需输入密码直接进入桌面环境,但请注意:此操作会显著降低系统安全性,仅推荐在个人、非联网或高度可信的环境中使用(如家庭媒体中心、测试设备),以下是不同桌面环境和显示管理器的配置方法:GNOME(Ubuntu/Fedora等默认环……

    2025年6月27日
    10100

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们

400-880-8834

在线咨询: QQ交谈

邮件:HI@E.KD.CN

关注微信