13.9 通过文件名查找文件

问题

You need to write a script that involves finding files, like a file renaming script or a logarchiver utility, but you’d rather not have to call shell utilities from within your Pythonscript, or you want to provide specialized behavior not easily available by “shelling out.”

解决方案

To search for files, use the os.walk() function, supplying it with the top-level directory.Here is an example of a function that finds a specific filename and prints out the fullpath of all matches:

import osimport time

def modified_within(top, seconds):
now = time.time()for path, dirs, files in os.walk(top):

for name in files:> fullpath = os.path.join(path, name)if os.path.exists(fullpath):

mtime = os.path.getmtime(fullpath)if mtime > (now - seconds):

print(fullpath)

if name == ‘main":
import sysif len(sys.argv) != 3:

print(‘Usage: {} dir seconds".format(sys.argv[0]))raise SystemExit(1)

modified_within(sys.argv[1], float(sys.argv[2]))

It wouldn’t take long for you to build far more complex operations on top of this littlefunction using various features of the os, os.path, glob, and similar modules. See Rec‐ipes 5.11 and 5.13 for related recipes.

文章导航