【问题标题】:Get all files from my C drive - Python从我的 C 盘获取所有文件 - Python
【发布时间】:2016-07-31 20:42:16
【问题描述】:

这是我尝试做的事情: 我想获取 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 块。

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

非常感谢您的 cmets。

【问题讨论】:

  • 我尝试在本地运行该代码(在 UNIX 系统上使用/ 而不是C:/),它运行良好,只是碰巧没有一个文件大于 35 MB在那个目录中。您确定C:/ 内有超过 35MB 的文件吗?您的代码只会直接分析 C:/ 文件夹中的文件,而不是递归遍历它以查看驱动器中的所有文件。
  • @DavidGomes:你确定最后那句话吗?根据该函数,它应该为文件夹递归调用自身。
  • 是的,我错了。你应该这样做 os.path.isdir(directory + file) 然后因为 os.path.isdir 只有在你给它完整路径的情况下才能知道它是否是一个目录。

标签: python windows python-2.7 python-3.x


【解决方案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()

【讨论】:

  • 您应该使用os.path.join(directory, file) 以获得最大的可靠性。当然,OP 也应该首先使用os.walk
  • 这将在 3.5+ 中使用os.walk 表现得更好,后者切换到使用os.scandir 而不是os.listdir。对于 Windows,它还需要使用 Unicode 字符串,并且驱动器 C: 上的基本路径应该是 u"\\\\?\\C:\\"。这允许路径长度最多约为 32,760 个字符,而不是默认限制为 260 个字符。
  • 可以看看os.walk方式的样例吗?
猜你喜欢
  • 2021-11-10
  • 1970-01-01
  • 2017-09-19
  • 2021-04-03
  • 1970-01-01
  • 1970-01-01
  • 2011-05-16
  • 2020-12-13
  • 2022-01-13
相关资源
最近更新 更多