有没有更好的方法删除给定子目录中的所有.py和.pyc文件?

时间:2019-01-28 16:57:38

标签: python django loops django-migrations coding-efficiency

我写了一个脚本来删除给定子目录“ migrations”中的所有.py和.pyc文件。最终目标是从django项目中删除所有迁移文件,因此有多个名为“ migrations”的子文件夹,我想删除所有.py和.pyc( init .py除外)从这些文件夹中。我在下面编写的脚本可以工作,但是我是python的新手,所以我认为必须有比所有嵌套循环更好的方法。有什么建议么?这是一个Windows系统,对我来说使事情复杂化。


class RootVC: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupTabBarLayout()

    }

    private func setupTabBarLayout() {
        // 1. Profile page
        let profileVC = ProfileVC()
        let profileVCBarItem = UITabBarItem(title: "Profil", image: UIImage(named: "profile_icon"), tag: 1)
        profileVC.tabBarItem = profileVCBarItem

        // 2. Search
        let searchVC = SearchVC()
        let searchVCBarItem = UITabBarItem(title: "Search", image: UIImage(named: "search_icon"), tag: 2)
        searchVC.navigationItem.leftBarButtonItem = nil
        searchVC.tabBarItem = searchVCBarItem

        // 3. Meet
        let meetVC = MeetVC()
        let meetVC = SearchResultsVC()
        let meetVCBarItem = UITabBarItem(title: "Meet", image: UIImage(named: "meet_icon"), tag: 3)
        meetVC.tabBarItem = meetVCBarItem

        // 4. Activities
        let activitiesVC = ActivitiesVC()
        let activitiesVCBarITem = UITabBarItem(title: "Activities", image: UIImage(named: "activities_icon"), tag: 4)
        activitiesVC.tabBarItem = activitiesVCBarITem

        // VC Setup
        viewControllers = [profileVC, searchVC, meetVC, activitiesVC]
        // Design settings
        self.tabBar.backgroundColor = .lightButtonBg
        self.tabBar.barTintColor = .darkMagenta
        self.tabBar.tintColor = .customWhite
        self.tabBar.unselectedItemTintColor = .lightButtonBg
        self.tabBar.isTranslucent = false

    }

3 个答案:

答案 0 :(得分:1)

一个os.walk应该为您完成大部分工作;您唯一需要做的另一循环是遍历它进入的每个目录中的files。您当然不需要嵌套 os.walk

答案 1 :(得分:1)

对于正在由外部os.walk()循环处理的子目录调用os.walk(),您正在做双重工作。

您需要测试的是migrations是否是要处理的目录的当前root路径中的元素:

def delete_py(path, subfolder):
    for root, dirs, files in os.walk(path):
        if subfolder in root.split(os.sep):
            # has subfolder as a directory name in the path, delete .py files here
            for file in files:
                if file == '__init__.py':
                    continue
                if file.endswith(('.py', '.pyc')):
                    os.unlink(os.path.join(root, file))

您还可以仅使用带有glob module的递归glob模式:

from itertools import chain

def delete_py(path, subfolder):
    pyfiles = glob.iglob(f'**/{subfolder}/**/*.py', recursive=True)
    pycfiles = glob.iglob(f'**/{subfolder}/**/*.pyc', recursive=True)
    for filename in chain(pyfiles, pycfiles):
        if os.path.basename(filename) == '__init__.py':
            continue
        os.unlink(filename)

答案 2 :(得分:0)

只需使用

  • 对于Linux “找到。-name” * .pyc“ -delete”
  • 对于Windows: “ DEL / S / Q * .pyc”