You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python比较源文件夹与目标文件夹中同名文件的大小?

Python实现两个同名文件夹间的文件大小对比

可以通过遍历源文件夹中的文件,逐一匹配目标文件夹内的同名文件,分别获取大小后进行对比,以下是具体实现方案:

核心步骤

  • 定义源文件夹与目标文件夹的实际路径
  • 遍历源文件夹中的所有文件(自动跳过子目录)
  • 对每个文件,拼接目标文件夹中的对应文件路径
  • 检查目标文件是否存在,若存在则对比两者大小,不存在则标记异常
  • 输出每个文件的对比结果

完整代码示例

import os

# 替换为你的源文件夹和目标文件夹路径
source_dir = r'C:\Your\Source_Folder_Path'
target_dir = r'C:\Your\Target_Folder_Path'

# 遍历源文件夹内的所有条目
for filename in os.listdir(source_dir):
    source_file = os.path.join(source_dir, filename)
    # 只处理文件,跳过子文件夹
    if os.path.isfile(source_file):
        target_file = os.path.join(target_dir, filename)
        
        # 检查目标文件是否存在且为文件类型
        if os.path.exists(target_file) and os.path.isfile(target_file):
            # 获取两个文件的字节大小
            source_size = os.path.getsize(source_file)
            target_size = os.path.getsize(target_file)
            
            # 对比并输出结果
            if source_size == target_size:
                print(f"文件 {filename}: 大小一致,均为 {source_size} 字节")
            elif source_size > target_size:
                print(f"文件 {filename}: 源文件更大 | 源: {source_size} 字节 / 目标: {target_size} 字节")
            else:
                print(f"文件 {filename}: 目标文件更大 | 源: {source_size} 字节 / 目标: {target_size} 字节")
        else:
            print(f"文件 {filename}: 目标文件夹中无对应文件")

补充说明

  • 用os.path.join拼接路径,避免因Windows/Linux路径分隔符差异导致的错误
  • 加入文件存在性检查,防止因目标文件缺失触发异常
  • 若需要递归对比子文件夹中的文件,可以改用os.walk遍历,同时处理子目录的路径拼接

内容的提问来源于stack exchange,提问作者Anson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 05:03:27