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