这是我尝试做的:我想得到一个列表,列出了我的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。
有人能告诉我我做错了什么以及为什么(学习是我的目标)。怎么解决?
非常感谢您的评论。
我修复了你的代码。你的问题是os.path.isdir
只能知道某个目录是否是一个目录,如果它收到它的完整路径。所以,我将代码更改为以下内容并且可以正常工作。 os.path.getsize
和os.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()