2016-07-31 52 views
0

下面是我尝试做的: 我想获取C驱动器中所有重量超过35 MB的文件的列表。从我的C驱动器获取所有文件 - Python

这里是我的代码:

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 !") 

出于某种原因,解释不会在if块中去“getAllFileFromDirectory”。

有人能告诉我我做错了什么,为什么(学习是我的目标)。如何解决它?

非常感谢您的意见。

+0

我试着在本地运行该代码(在UNIX系统上,所以用'/'而不是'C:/'),它运行得很完美,它恰巧发生的情况是没有一个文件大于35 MB在那个目录中。你确定你有超过35MB的文件,在'C:/'里面?您的代码只会直接在'C:/'文件夹内分析文件,而不是递归地遍历它以查看驱动器中的所有文件。 –

+0

@DavidGomes:你确定最后的陈述吗?根据该函数,它应该为文件夹递归调用自身。 – usr2564301

+1

是的,我错了。你应该执行'os.path.isdir(directory + file)',因为'os.path.isdir'只能知道某个目录是否是一个目录,如果你给它的完整路径。 –

回答

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() 
+2

你应该使用'os.path.join(目录,文件)'来获得最大的可靠性。当然,OP也应该首先使用'os.walk'。 –

+1

使用'os.walk'可以在3.5+以上执行,而使用'os.scandir'而不是'os.listdir'。对于Windows,它还需要使用Unicode字符串和驱动器C上的基本路径:应该是'u'\\\\\\\\ C:\\“'。这允许路径长度达到约32,760个字符,而默认限制为260个字符。 – eryksun

+0

是否可以看看os.walk方式的示例? – programminator

相关问题