使用查找大于300MB的文件os.步行在Python中?

2024-04-25 21:12:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了这个代码来遍历一个目录并查找大于300MB的文件。你知道吗

但是,我得到了很多重复的值,并且重复的数量在不同的文件中有所不同。有没有人能解释一下或者改进一下代码?你知道吗

import os

path = 'C:\\Users\\brentond\\Desktop\\Lower Thames Crossing'
for foldername, subfolders, filenames in os.walk(path):
    for subfolder in subfolders:
        for filename in filenames:
            if os.path.getsize(os.path.join(foldername, filename))>300000000:
                print(foldername + '\\' + filename)

Tags: 文件path代码inimport目录for数量
2条回答

跳过子文件夹循环。你知道吗

遍历已遍历子文件夹。你知道吗

每个文件夹都将被foldername精确地保存一次。对于每个文件夹,其直接子文件将以文件名的形式出现,每一次。你知道吗

它的直接子文件夹将在子文件夹中显示,每个子文件夹一次。您不需要在子文件夹上循环,除非您想直接对该文件夹执行某些操作,而不是检查其内容。你知道吗

你不必亲自浏览子文件夹,walk会帮你完成。你知道吗

从文件中:

os.walk(top, topdown=True, onerror=None, followlinks=False)

Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

(我的重点)

所以,只要做:

import os

path = 'C:\\Users\\brentond\\Desktop\\Lower Thames Crossing'
for foldername, subfolders, filenames in os.walk(path):
    for filename in filenames:
        if os.path.getsize(os.path.join(foldername, filename))>300000000:
            print(foldername + '\\' + filename)

相关问题 更多 >