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启动命令行有哪些高效方法?

    图形界面下启动命令行(最常用)适用于带桌面环境(如GNOME、KDE)的Linux发行版(Ubuntu、Fedora等),快捷键启动按 Ctrl + Alt + T(多数发行版默认快捷键),立即弹出终端窗口,可直接输入命令,菜单启动点击桌面左上角“活动”(Activities)或“应用程序菜单”,搜索关键词:t……

    2025年6月15日
    14400
  • Linux系统如何查看CPU与内存的使用情况?

    在Linux系统中,监控CPU和内存的使用情况是系统管理和性能优化的基础工作,通过合理的命令和工具,管理员可以实时了解系统资源状态,及时发现瓶颈并采取应对措施,本文将详细介绍Linux查看CPU和内存信息的多种方法,包括常用命令、参数解析及实际应用场景,查看CPU信息的方法CPU作为系统的核心组件,其使用率、核……

    2025年9月22日
    8500
  • 如何快速掌握递归搜索基础语法?

    在Linux系统中,文件搜索是日常管理的关键操作,以下是专业、高效且安全的搜索方法,涵盖基础到进阶场景,所有命令均通过实际环境验证(基于主流Linux发行版):按文件名/属性搜索:find 命令(最强大)适用场景:精准定位文件位置、按类型/大小/时间过滤# 常用示例:find /home -name &quot……

    2025年7月31日
    13000
  • 为何必须更新软件源?

    为什么需要升级 Linux 内核?升级内核可获取新硬件支持、安全补丁、性能优化及功能改进(如文件系统增强、虚拟化升级),但生产环境需谨慎:务必提前备份数据,避免不兼容导致系统崩溃,检查当前内核版本uname -r # 示例输出:5.4.0-150-generic主流发行版升级方法(推荐)▶ Ubuntu/Deb……

    2025年7月19日
    12200
  • Linux如何永久删除sudo用户?

    方法1:仅移除sudo权限(保留用户账户)适用于需保留用户但撤销管理员权限的场景,查看用户所属组执行命令确认用户是否在sudo或wheel组(不同系统组名可能不同):groups 用户名 # groups john若输出包含sudo或wheel,则需移除,移除sudo组使用gpasswd命令从组中删除用户:su……

    2025年6月28日
    11500

发表回复

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

联系我们

400-880-8834

在线咨询: QQ交谈

邮件:HI@E.KD.CN

关注微信