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

相关推荐

  • ARM架构如何运行Linux操作系统?

    ARM架构作为当前嵌入式设备、移动终端及部分服务器的主流处理器架构,凭借其低功耗、高性能的特点,与Linux系统的开源、灵活特性高度契合,广泛应用于从物联网设备到边缘计算的各种场景,要在ARM平台上运行Linux系统,需从硬件选型、系统移植、配置优化等多个环节入手,以下将详细阐述具体过程与关键要点,硬件基础:A……

    2025年10月8日
    10500
  • Linux网关信息如何查看?

    使用 ip route 命令(推荐)适用场景:现代Linux发行版(CentOS 7+/Ubuntu 18.04+)步骤:打开终端,执行: ip route show default或简写为:ip r输出解析: default via 192.168.1.1 dev eth0 proto static metr……

    2025年7月19日
    14000
  • Linux如何查看驱动程序信息?

    查看已加载的驱动模块驱动在Linux中通常以内核模块(.ko文件)形式存在,以下命令可查看当前加载的模块:lsmod 命令直接列出所有已加载模块,显示模块名、大小及依赖关系:lsmod输出示例:Module Size Used bynvidia 35323904 203i915 2457600 5usb_sto……

    2025年8月3日
    11500
  • Linux环境下如何使用itoa函数?整数转字符串的实现方法是什么?

    在Linux环境下,将整数转换为字符串(即实现类似Windows中itoa的功能)是常见的编程需求,虽然标准C库中没有直接名为itoa的函数(该函数是MSVC等编译器的非标准扩展),但Linux提供了多种替代方案,包括标准库函数、自定义函数实现等,本文将详细介绍这些方法的使用场景、代码实现及注意事项,Linux……

    2025年10月1日
    10500
  • Linux如何正确删除一个用户账户及关联文件?

    在Linux系统中,用户管理是系统运维的基础操作之一,删除用户是常见需求,可能因员工离职、账户闲置或安全策略调整等原因触发,正确删除用户不仅能释放系统资源,还能避免潜在的安全风险,本文将详细讲解Linux中删除用户的完整流程、注意事项及不同场景下的操作方法,帮助用户安全、高效地完成用户删除任务,删除用户前的准备……

    2025年9月10日
    12600

发表回复

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

联系我们

400-880-8834

在线咨询: QQ交谈

邮件:HI@E.KD.CN

关注微信