[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

so is portable; run this to delete .pyc's from an old Python release;
"""


import os, sys, find # here, gets Tools.find


count = 0
for filename in find.find('*.pyc', sys.argv[1]):
count += 1
print(filename)
os.remove(filename)


print('Removed %d .pyc files' % count)


When run, all bytecode files in the tree rooted at the passed-in directory name are
removed as before; this time, though, our script works just about everywhere Python
does:


C:\...\PP4E\Tools> cleanpyc-find-py.py.
.\find.pyc
.\visitor.pyc
.\__init__.pyc
Removed 3 .pyc files

This works portably, and it avoids external program startup costs. But find is really
just half the story—it collects files matching a name pattern but doesn’t search their
content. Although extra code can add such searching to a find’s result, a more manual
approach can allow us to tap into the search process more directly. The next section
shows how.


A Python Tree Searcher


After experimenting with greps and globs and finds, in the end, to help ease the task
of performing global searches on all platforms I might ever use, I wound up coding a
task-specific Python script to do most of the work for me. Example 6-17 employs the
following standard Python tools that we met in the preceding chapters: os.walk to visit
files in a directory, os.path.splitext to skip over files with binary-type extensions, and
os.path.join to portably combine a directory path and filename.


Because it’s pure Python code, it can be run the same way on both Linux and Windows.
In fact, it should work on any computer where Python has been installed. Moreover,
because it uses direct system calls, it will likely be faster than approaches that rely on
underlying shell commands.


Example 6-17. PP4E\Tools\search_all.py


"""
################################################################################
Use: "python ...\Tools\search_all.py dir string".
Search all files at and below a named directory for a string; uses the
os.walk interface, rather than doing a find.find to collect names first;
similar to calling visitfile for each find.find result for "*" pattern;


Searching Directory Trees | 327
Free download pdf