如何创建递归Python脚本来对文件和文件夹进行排序?

时间:2015-09-11 21:45:00

标签: python sorting recursion scripting

所以我制作了这个脚本,将文件夹分类到不同类型的子文件夹中,并且它有效!但是现在我希望它能够对我告诉它进行排序的文件夹中的文件夹进行排序。我试过递归,但它没有用?我的语法错了吗?另外,如何将目录中的x文件类型移动到我告诉脚本排序的文件夹中的适当排序文件夹中?如果这是有道理的。

这是我的代码:

#!/bin/python
import os
path = raw_input("Enter your folder you would like sorted: ")
def searchFolders(path):
    if os.path.exists(path): 
        dirList = os.listdir(path) 
        for filename in dirList: 
            if  ".jpg" in filename:
                if not os.path.exists(path + "Photos"):
                    os.makedirs(path + "Photos")
                os.rename(path + filename, path + "Photos/" + filename)
            elif ".pptx" in filename:
                if not os.path.exists(path + "Powerpoints"):
                    os.makedirs(path + "Powerpoints")
                os.rename(path + filename, path + "Powerpoints/" + filename)
            elif ".zip" in filename:
                if not os.path.exists(path + "Zip Files"):
                    os.makedirs(path + "Zip Files")
                os.rename(path + filename, path + "Zip Files/" + filename)
            elif ".dmg" in filename:
                if not os.path.exists(path + "Disk Images"):
                    os.makedirs(path + "Disk Images")
                os.rename(path + filename, path + "Disk Images/" + filename)
            elif ".mp3" in filename:
                if not os.path.exists(path + "Music"):
                    os.makedirs(path + "Music")
                os.rename(path + filename, path + "Music/" + filename)
            elif ".pdf" in filename:
                if not os.path.exists(path + "Pdf"):
                    os.makedirs(path + "Pdf")
                os.rename(path + filename, path + "Pdf/" + filename)
            elif ".cpp" in filename:
                if not os.path.exists(path + "C++"):
                    os.makedirs(path + "C++")
                os.rename(path + filename, path + "C++/" + filename)
            elif ".psd" in filename:
                if not os.path.exists(path + "Photoshop"):
                    os.makedirs(path + "Photoshop")
                os.rename(path + filename, path + "Photoshop/" + filename)
            elif ".dng" in filename:
                if not os.path.exists(path + "Photos/Raw Photos"):
                    os.makedirs(path + "Photos/Raw Photos")
                os.rename(path + filename, path + "Photos/Raw Photos/" + filename)
            elif not "." in filename:
                folderPath = path + filename
                searchFolders(folderPath)   
            else: 
                if not os.path.exists(path + "Random"):
                    os.makedirs(path + "Random")
                os.rename(path + filename, path + "Random/" + filename)

        print "Sorting Complete"
    else:
        print "Folder Does not exist"

1 个答案:

答案 0 :(得分:1)

ComposerServiceProvider

应该让你到达你想要的地方......