加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

对Python 文件夹遍历和文件查找的实例讲解

发布时间:2020-12-16 21:03:40 所属栏目:Python 来源:网络整理
导读:实例如下所示: # -*- coding: utf-8 -*-#to find where use the table on xxxxx xxxxxx production env'''在项目中我们元数据管理的不是很好,如果先知道一张表在哪里用过,就需要写个程序去遍历下'''import osimport os.pathrootdir = "C:UsersIBM_ADM

实例如下所示:

# -*- coding: utf-8 -*-
#to find where use the table on xxxxx xxxxxx  production env
'''
在项目中我们元数据管理的不是很好,如果先知道一张表在哪里用过,就需要写个程序去遍历下
'''
import os
import os.path
rootdir =  "C:UsersIBM_ADMINIBMrationalsdpworkspace"#   # 指明被遍历的文件夹
query = "xxxxxxxxx"              
def walk_all_files(rootdir,query):
  for parent,dirnames,filenames in os.walk(rootdir):  #for循环自动完成递归枚举 #三个参数:分别返回1.父目录(当前路径) 2.所有文件夹名字(不含路径) 3.所有文件名字
    for dirname in dirnames:             #输出文件夹信息
      #print "parent is:" + parent
      #print "dirname is :" + dirname
      pass
    for filename in filenames:            #输出文件信息
      #print "parent is :" + parent
      #print "filename is:" + filename
      #print "the full name of the file is :" + os.path.join(parent,filename)
      is_file_contain_word(os.path.join(parent,filename),query)
def is_file_contain_word(file_,query_word):
  #print 2222211
  if query_word in open(file_).read() :
    print file_
    filecontext = open(file_).read()
    lines = filecontext.split('n')         # python打印关键词所在行
    for line in lines:
      if query_word in line:
        print line
walk_all_files(rootdir,query)
print "done"
'''
http://www.iplaypy.com/jichu/note.html
please explain os.walk() :
walk()方法语法格式如下:
os.walk(top[,topdown=True[,onerror=None[,followlinks=False]]])os.walk(top[,followlinks=False]]])
参数
  top -- 根目录下的每一个文件夹(包含它自己),产生3-元组 (dirpath,filenames)【文件夹路径,文件夹名字,文件名】。
  topdown --可选,为True或者没有指定,一个目录的的3-元组将比它的任何子文件夹的3-元组先产生 (目录自上而下)。如果topdown为 False,一个目录的3-元组将比它的任何子文件夹的3-元组后产生 (目录自下而上)。
  onerror -- 可选,是一个函数; 它调用时有一个参数,一个OSError实例。报告这错误后,继续walk,或者抛出exception终止walk。
  followlinks -- 设置为 true,则通过软链接访问目录。
返回值
该方法没有返回值。
'''

以上这篇对Python 文件夹遍历和文件查找的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。

您可能感兴趣的文章:

  • Python遍历目录中的所有文件的方法
  • Python遍历某目录下的所有文件夹与文件路径
  • Python遍历文件夹和读写文件的实现方法
  • Python遍历文件夹和读写文件的实现代码

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读