【问题标题】:Iterating through directories and checking the file's size遍历目录并检查文件的大小
【发布时间】:2012-05-13 01:17:14
【问题描述】:

我想遍历目录和子目录,并检查每个文件的文件大小。如果它与定义的文件大小匹配,它将被删除。

我知道,我必须使用 os.walk,但我不太确定,以哪种方式。

我用于目录列表的代码是:

import os
path = "C:\\Python27"
i=0
for (path,dirs,files) in os.walk(path):
    print files
    i=i+1
    if i>10:
        break

【问题讨论】:

  • Directory listing in Python 的可能重复项
  • 你真的应该在寻求帮助之前尝试一下
  • 我可以列出所有目录和文件,但我想检查每个目录中的特定文件大小。
  • os.path.getsize 函数是你的朋友。只需调用os.path.getsize(yourfilepath) 以返回字节大小
  • 谢谢!使用 os.path.getsize() 让它工作。

标签: python


【解决方案1】:

试试这个:

import os

for root, dirs, files in os.walk('/path/to/dir', topdown=False):
    for name in files:
        f = os.path.join(root, name)
        if os.path.getsize(f) == filesize:
            os.remove(f)

【讨论】:

  • 非常感谢。有效!如果我还想检查与目录名称相同的目录中的文件名怎么办。假设,检查 mydir 目录中名为 mydir.txt 的文件。
  • @RobertShane 都一样,添加另一个条件类似于if root.endswith(name[:name.rindex('.')]):
【解决方案2】:

这应该可行:

from __future__ import print_function # => For Python 2.5 - 2.7
import os

def delete_files_with_size(dirname, size):
    for root, _, files in os.walk(dirname):
        for filename in files:
            filepath = os.path.join(root, filename)
            if os.path.getsize(filepath) == size:
                print('removing {0}'.format(filepath))
                os.remove(filepath)

就像你说的,os.walk 是处理这类事情的方法。 os.walk 返回一个包含根路径、目录列表和文件列表的元组。由于我们对目录不感兴趣,所以我们在解压返回值时使用常规的_ 变量名。

由于文件名本身不包含路径,您可以将os.path.joinrootfilename 一起使用。 os.path.getsize 将返回文件的大小,如果文件大小匹配,os.remove 将删除该文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多