Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >python 查找文件、删除、搜索类 脚本

python 查找文件、删除、搜索类 脚本

作者头像
用户5760343
发布于 2022-05-13 03:03:30
发布于 2022-05-13 03:03:30
65500
代码可运行
举报
文章被收录于专栏:sktjsktj
运行总次数:0
代码可运行

搜集

""" Use: "python ...\Tools\visitor_collect.py searchstring rootdir". CollectVisitor simply collects a list of all files containing a search string, for display or later processing (e.g., replacement, auto-editing); pass in a test filename extensions list to constructor to override the default in SearchVisitor; this is roughy like find+grep for text exts; """

import sys from visitor import SearchVisitor

class CollectVisitor(SearchVisitor): """ collect names of files containing a string; run this and then fetch its obj.matches list """ def init(self, searchstr, testexts=None, trace=1): self.matches = [] if testexts != None: self.testexts = testexts SearchVisitor.init(self, searchstr, trace) def visitmatch(self, fname, text): self.matches.append(fname)

if name == 'main': visitor = CollectVisitor(sys.argv[1]) visitor.run(startDir=sys.argv[2]) matches = visitor.matches print('Found', len(matches), 'files:') for fname in matches: print(fname)

""" Change all "#!...python" source lines at the top of Unix scripts to new line in all files in all dirs at and below a root; command line args are the root (default='.'), new #! line text (default=changeToDefault), and any text to run list-only mode (default=no);

could skip binary filename extensions explicitly, but try handler works; changes all #! first lines that name python, which is more accurate than a simple visitor_replace.py; example usage -- convert all scripts in book examples tree, list file to be changed in a tree, convert all to default: C:...\PP4E>python Tools\visitor_poundbang.py . #!\MyPy31\python > out.txt C:...\PP4E\Tools>python visitor_poundbang.py C:\temp\PP3E - - | more C:...\PP4E\Tools>python visitor_poundbang.py C:\temp\PP3E """

import sys from visitor import FileVisitor # reuse the walker classes changeToDefault = '#!\Python31\python.exe' # used if no cmdline arg

class PoundBangFixer(FileVisitor): def init(self, changeTo=changeToDefault, listonly=False, trace=0): FileVisitor.init(self, trace=trace) self.changeTo = changeTo self.listOnly = listonly self.clist = []

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
def visitfile(self, fullname):
    FileVisitor.visitfile(self, fullname)
    try:
        lines = open(fullname, 'r').readlines()      # fails for binary files
    except UnicodeDecodeError:
        if self.trace > 0: print('Skipped non-text file:', fullname)
    else:
        if (len(lines) > 0            and
            lines[0].startswith('#!') and            # or lines[0][0:2] == '#!'
            'python' in lines[0]                     # or lines[0].find() != -1
            ):
            self.clist.append(fullname)
            if not self.listOnly:
                lines[0] = self.changeTo + '\n'
                open(fullname, 'w').writelines(lines)

if name == 'main': if input('Are you sure?') != 'y': sys.exit() rootdir = sys.argv[1] if len(sys.argv) > 1 else '.' changeto = sys.argv[2] if len(sys.argv) > 2 else changeToDefault listonly = len(sys.argv) > 3 walker = PoundBangFixer(changeto, listonly) walker.run(rootdir) print('Visited %d files and %d dirs,' % (walker.fcount, walker.dcount), end=' ') print('found' if listonly else 'changed', len(walker.clist), 'files') for fname in walker.clist: print(fname)

删除

"Remove all .pyc bytecode files in a tree (visitor version)"

import sys, os from visitor import FileVisitor

class CleanPyc(FileVisitor): def init(self, trace=0): FileVisitor.init(self, context=0, trace=trace)

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
def visitfile(self, filepath):
    FileVisitor.visitfile(self, filepath)
    if filepath.endswith('.pyc'):
        print(filepath) 
        #os.remove(filepath)
        self.context += 1

if name == 'main': walker = CleanPyc() walker.run(sys.argv[1] if len(sys.argv) > 1 else '.') print('Visited %d files and %d dirs' % (walker.fcount, walker.dcount)) print('Removed %d files' % walker.context)


查找大文件

"find biggest/smallest .py files in a tree (visitor version)"

import sys, os, pprint from visitor import FileVisitor

class BigPy(FileVisitor): def init(self, trace=0): FileVisitor.init(self, context=[], trace=trace)

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
def visitfile(self, filepath):
    FileVisitor.visitfile(self, filepath)
    if filepath.endswith('.py'):
        print(filepath) 
        self.context.append((os.path.getsize(filepath), filepath))

if name == 'main': walker = BigPy() walker.run(sys.argv[1] if len(sys.argv) > 1 else '.') print('Visited %d files and %d dirs' % (walker.fcount, walker.dcount)) walker.context.sort() pprint.pprint(walker.context[:2]) pprint.pprint(walker.context[-2:])


visitor.py

""" #################################################################################### Test: "python ...\Tools\visitor.py dir testmask [string]". Uses classes and subclasses to wrap some of the details of os.walk call usage to walk and search; testmask is an integer bitmask with 1 bit per available self-test; see also: visitor_*/.py subclasses use cases; frameworks should generally use__X pseudo private names, but all names here are exported for use in subclasses and clients; redefine reset to support multiple independent walks that require subclass updates; #################################################################################### """

import os, sys

class FileVisitor: """ Visits all nondirectory files below startDir (default '.'); override visit* methods to provide custom file/dir handlers; context arg/attribute is optional subclass-specific state; trace switch: 0 is silent, 1 is directories, 2 adds files """ def init(self, context=None, trace=2): self.fcount = 0 self.dcount = 0 self.context = context self.trace = trace

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
def run(self, startDir=os.curdir, reset=True):
    if reset: self.reset()
    for (thisDir, dirsHere, filesHere) in os.walk(startDir):
        self.visitdir(thisDir)
        for fname in filesHere:                          # for non-dir files
            fpath = os.path.join(thisDir, fname)         # fnames have no path
            self.visitfile(fpath)

def reset(self):                                         # to reuse walker
    self.fcount = self.dcount = 0                        # for independent walks

def visitdir(self, dirpath):                             # called for each dir
    self.dcount += 1                                     # override or extend me
    if self.trace > 0: print(dirpath, '...')

def visitfile(self, filepath):                           # called for each file
    self.fcount += 1                                     # override or extend me
    if self.trace > 1: print(self.fcount, '=>', filepath)

class SearchVisitor(FileVisitor): """ Search files at and below startDir for a string; subclass: redefine visitmatch, extension lists, candidate as needed; subclasses can use testexts to specify file types to search (but can also redefine candidate to use mimetypes for text content: see ahead) """

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
skipexts = []
testexts = ['.txt', '.py', '.pyw', '.html', '.c', '.h']  # search these exts

skipexts = ['.gif', '.jpg', '.pyc', '.o', '.a', '.exe'] # or skip these exts

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
def __init__(self, searchkey, trace=2):
    FileVisitor.__init__(self, searchkey, trace)
    self.scount = 0

def reset(self):                                         # on independent walks
    self.scount = 0

def candidate(self, fname):                              # redef for mimetypes
    ext = os.path.splitext(fname)[1]
    if self.testexts:
        return ext in self.testexts                      # in test list
    else:                                                # or not in skip list
        return ext not in self.skipexts
     
def visitfile(self, fname):                              # test for a match
    FileVisitor.visitfile(self, fname)
    if not self.candidate(fname):
        if self.trace > 0: print('Skipping', fname)
    else:
        text = open(fname).read()                        # 'rb' if undecodable
        if self.context in text:                         # or text.find() != -1
            self.visitmatch(fname, text)
            self.scount += 1

def visitmatch(self, fname, text):                       # process a match
    print('%s has %s' % (fname, self.context))           # override me lower

if name == 'main': # self-test logic dolist = 1 dosearch = 2 # 3=do list and search donext = 4 # when next test added

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
def selftest(testmask):
    if testmask & dolist:
       visitor = FileVisitor(trace=2)
       visitor.run(sys.argv[2])
       print('Visited %d files and %d dirs' % (visitor.fcount, visitor.dcount))

    if testmask & dosearch:
       visitor = SearchVisitor(sys.argv[3], trace=0)
       visitor.run(sys.argv[2])
       print('Found in %d files, visited %d' % (visitor.scount, visitor.fcount))

selftest(int(sys.argv[1]))    # e.g., 3 = dolist | dosearch
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
【C++高阶】二叉搜索树的全面解析与高效实现
二叉搜索树(BST,Binary Search Tree)又称二叉排序树,是一种特殊的二叉树,它或者是一棵空树,或者是具有以下性质的二叉树:
IsLand1314
2024/10/15
1470
【C++高阶】二叉搜索树的全面解析与高效实现
这是一棵适合搜索二叉树
二叉搜索树(Binary Search Tree)又称为二叉查找树,是一种常用的数据结构。它是一棵空树,或者是具有以下性质的二叉树:
初阶牛
2023/11/23
1590
这是一棵适合搜索二叉树
【搜索二叉树】—— 我与C++的不解之缘(二十一)
在map/set/multimap/multidset等系列式容器底层就是搜索二叉树,其他map/set不支持数据冗余(不支持插入相同的值);multimap/multiset支持数据冗余。
星辰与你
2024/12/29
1360
【搜索二叉树】—— 我与C++的不解之缘(二十一)
C++:二叉搜索树
二叉搜索树(BST, Binary Search Tree)又叫做二叉排序树,它可以是一颗空树,其性质如下:
二肥是只大懒蓝猫
2023/03/30
2970
C++:二叉搜索树
C++之搜索二叉树
本文介绍了二叉搜索树的相关概念,主要介绍了如何使用和实现搜索二叉树以及搜索二叉树具体的例题练习。
摘星
2023/04/28
5540
C++之搜索二叉树
C++二叉搜索树与KV模型
二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树: 若它的左子树不为空,则左子树上所有节点的值都小于根节点的值 若它的右子树不为空,则右子树上所有节点的值都大于根节点的值 它的左右子树也分别为二叉搜索树
有礼貌的灰绅士
2023/04/12
4280
C++二叉搜索树与KV模型
C++两种方法实现二叉搜索树
a.从根节点出发,如果要找的值大于当前的节点值,去右边找, 如果要找的值小于当前的节点值,则去左边找, 如果相等则表示找到了。 b.如果值存在的话,最多查找高度次
Yui_
2024/10/15
1070
C++两种方法实现二叉搜索树
C++【二叉搜索树】
时隔多日,又回到了二叉树的学习中,在 C++ 进阶中,我们首先要学习 二叉搜索树,重新捡起二叉树的相关知识,然后会学习 AVL 树 及 红黑树,最后会用红黑树封装实现库中的 set 和 map,作为 C++ 进阶中的难度最高峰,整个学习过程非常艰辛,但 关关难过关关过,让我们先从比较简单的 二叉搜索树 开始学习
北 海
2023/07/01
2060
C++【二叉搜索树】
【C++】从零开始构建二叉搜索树
普通的二叉树没有特别的性质,今天我们就来赋予其一个全新的性质来满足高速搜索的需求 ,并为后序的map与set做铺垫 ,二叉搜索树的特性了解,有助于更好的理解map和set的特性
叫我龙翔
2024/05/26
1440
【C++】从零开始构建二叉搜索树
二叉搜索树
二叉搜索树是在普通的二叉树上进阶的,所以咱们今天的内容也可以说是,数据结构二叉树的进阶。二叉搜索树可谓是起到了承上启下的作用,向前承接了数据结构的二叉树,向后对于map和set的模拟实现也起到了启示作用。
小灵蛇
2024/06/06
1090
二叉搜索树
【C++深度探索】二叉搜索树的全面解析与高效实现
二叉搜索树(BST,Binary Search Tree)又称二叉排序树,是一种特殊的二叉树,它或者是一棵空树,或者是具有以下性质的二叉树:
大耳朵土土垚
2024/07/25
1500
【C++深度探索】二叉搜索树的全面解析与高效实现
C++-你知道二叉搜索树吗?(循环版)
 在二叉搜索树中,右子树上的任意一个节点的值都大于当前节点的值,左子树上的任意一个节点的值都小于当前节点的值,所以查找值的时候效率就很高,在任意位置插入和删除数据也不需要挪动,而且搜索二叉树走中序遍历就是一个升序。
用户10923087
2024/03/02
1380
C++-你知道二叉搜索树吗?(循环版)
C++之二叉搜索树:高效与美的极致平衡
我们现在想去找这个4,4比8小,那么我们就没必要去右子树进行查找了,我们直接在左子树进行查找就行了
Undoom
2024/11/26
1010
C++之二叉搜索树:高效与美的极致平衡
C++二叉搜索树
【C++进阶学习】二叉树搜索树 零、前言 一、二叉搜索树概念 二、二叉搜索树的详解及模拟 1、二叉搜索树的结构 2、二叉树搜索树的构造和析构 3、二叉搜索树的查找 4、二叉搜索树的插入 5、二叉搜索树的删除 三、二叉搜索树的应用 零、前言 我们都知道二叉树只有附加上一些特性才具有实用的价值,而本章主要讲解二叉树进阶的内容-二叉搜索树 一、二叉搜索树概念 概念: 二叉搜索树(Binary Search Tree)又称二叉排序树,也称作二叉查找树它或者是一棵空树,或者是具有以下性质的二叉树 若
用户9645905
2022/11/30
3250
C++二叉搜索树
深入理解二叉搜索树(BST)
二叉搜索树(BST) 是一种具有特殊排序性质的二叉树,能够高效地执行数据检索、插入和删除操作。BST 的主要特性是,对于每个节点,其左子树中所有节点的值都小于或等于该节点的值,而右子树中所有节点的值都大于该节点的值。这一特性使得 BST 成为一种非常重要的数据结构,适用于搜索和排序任务,因为它提供了一种逻辑清晰且直接的方式来存储和检索有序数据。
用户11289931
2024/11/26
2780
今天你学C++了吗?——二叉搜索树
二叉搜索树是一种特殊的树形数据结构,它看起来像一棵普通的树,但每个节点都有一些特定的规则:
用户11352420
2025/03/20
810
今天你学C++了吗?——二叉搜索树
C++进阶:二叉搜索树介绍、模拟实现(递归迭代两版本)及其应用
假设我们插入以下元素:5, 3, 7, 1, 4, 6, 8,可以构建如下的二叉搜索树(BST):
是Nero哦
2024/03/21
2820
C++进阶:二叉搜索树介绍、模拟实现(递归迭代两版本)及其应用
【深入C++】二叉搜索树
二叉搜索树(Binary Search Tree, BST)是一种特殊的二叉树,其每个节点最多有两个子节点,分别称为左子节点和右子节点。BST具有以下性质:
用户11305458
2024/10/09
1490
【深入C++】二叉搜索树
【C++】二叉搜索树(概念、操作)
首先查找元素是否在二叉搜索树中,如果不存在,则返回, 否则要删除的结点可能分下面四种情 况:
秦jh
2024/07/19
1530
【C++】二叉搜索树(概念、操作)
【c++】二叉搜索树(BST)
每个节点有两个指针,分别指向它的左子节点和右子节点。如果子节点不存在,则这些指针为nullptr
用户11029103
2024/05/24
1220
【c++】二叉搜索树(BST)
相关推荐
【C++高阶】二叉搜索树的全面解析与高效实现
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验