从我的C盘获取所有文件 - Python

问题描述 投票:0回答:1

这是我尝试做的:我想得到一个列表,列出了我的C盘中重量超过35 MB的所有文件。

这是我的代码:

def getAllFileFromDirectory(directory, temp):
    files = os.listdir(directory)
    for file in files:
        if (os.path.isdir(file)):
            getAllFileFromDirectory(file, temp)
        elif (os.path.isfile(file) and os.path.getsize(file) > 35000000):
            temp.write(os.path.abspath(file))

def getFilesOutOfTheLimit():
    basePath = "C:/"
    tempFile = open('temp.txt', 'w')
    getAllFileFromDirectory(basePath, tempFile)
    tempFile.close()
    print("Get all files ... Done !")

出于某种原因,解释器不会进入'getAllFileFromDirectory'中的if-block。

有人能告诉我我做错了什么以及为什么(学习是我的目标)。怎么解决?

非常感谢您的评论。

python windows python-2.7 python-3.x
1个回答
1
投票

我修复了你的代码。你的问题是os.path.isdir只能知道某个目录是否是一个目录,如果它收到它的完整路径。所以,我将代码更改为以下内容并且可以正常工作。 os.path.getsizeos.path.isfile也是如此。

import os

def getAllFileFromDirectory(directory, temp):
    files = os.listdir(directory)

    for file in files:
        if (os.path.isdir(directory + file)):
            if file[0] == '.': continue  # i added this because i'm on a UNIX system

            print(directory + file)
            getAllFileFromDirectory(directory + file, temp)
        elif (os.path.isfile(directory + file) and os.path.getsize(directory + file) > 35000000):
            temp.write(os.path.abspath(file))

def getFilesOutOfTheLimit():
    basePath = "/"
    tempFile = open('temp.txt', 'w')

    getAllFileFromDirectory(basePath, tempFile)
    tempFile.close()
    print("Get all files ... Done !")

getFilesOutOfTheLimit()
© www.soinside.com 2019 - 2024. All rights reserved.