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

相关推荐

  • Debian如何快速安装Python工具链?

    通过包管理器安装(推荐)包管理器是Linux最核心的安装方式,自动解决依赖关系且安全性高(软件源自发行版官方仓库),不同发行版命令如下:Debian/Ubuntu系(APT)sudo apt update # 更新软件源列表sudo apt install 软件包名 # 安装软件(如 sudo apt inst……

    2025年6月27日
    20200
  • Linux如何快速统计用户数量?

    核心方法:通过系统文件直接统计统计所有本地用户 cat /etc/passwd | grep -vE '(nologin|false|sync|halt)' | wc -l原理:/etc/passwd 存储所有用户信息,grep -v 排除系统服务账户(如nologin等伪用户),输出示例:24……

    2025年7月15日
    20500
  • Linux系统如何运行Windows的bat脚本?

    在Linux系统中,直接运行Windows批处理脚本(.bat)是不可行的,因为Linux的操作系统内核和命令解释环境与Windows存在本质差异,Windows的.bat脚本依赖cmd.exe解释器执行,而Linux默认使用bash、zsh等shell,两者语法、命令集和系统调用方式完全不同,但通过特定方法……

    2025年10月7日
    24800
  • linux虚拟机如何更改ip

    Linux虚拟机中,可通过修改网络配置文件或使用命令(如ip addr)来

    2025年8月16日
    17600
  • Linux中如何设置网关?

    在Linux网络中,网关(Gateway)是连接本地网络与其他网络(如互联网)的关键设备,负责将本地数据包转发到目标网络,若未正确配置网关,会导致主机无法访问外部资源(如网站、远程服务器),本文将详细介绍Linux中临时与永久设置网关的方法,涵盖不同发行版的操作步骤,并附注意事项及常见问题解答,临时设置网关临时……

    2025年8月29日
    22400

发表回复

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

联系我们

400-880-8834

在线咨询: QQ交谈

邮件:HI@E.KD.CN

关注微信