python cookbook 13.9 通过文件名查找文件

#你要写一个涉及到文件查找操作的脚本,比如对日志归档文件的重命名工具,不想在python脚本中调用shell,或者你要实现一些shell不能做的功能
#查找文件可使用os.walk()函数,传一个顶级目录给它。下面是查找特定的文件名并答应所有符合条件的文件全路径:
import os
def findfile(start,name):
    for relpath,dirs,files in os.walk(start):
        if name in files:
            full_path=os.path.join(start,relpath,name)  #合并路径
            print(os.path.normpath(os.path.abspath(full_path)))  #abs()返回一个绝对路径,normpath()返回正常路径,可解决双斜杠对目录的多重引用的问题。
if __name__=='__main__':
    findfile('.\\','test.py')
#下面的函数打印所有最近被修改过的文件:
#!/usr/bin/env python3.3
import os
import 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 sys
    if len(sys.argv) != 3:
        print('Usage: {} dir seconds'.format(sys.argv[0]))
        raise SystemExit(1)
    modified_within(sys.argv[1], float(sys.argv[2]))

猜你喜欢

转载自blog.csdn.net/qq_21997625/article/details/91361381