python怎么遍历文件_如何用Python os.path.walk方法遍历搜索文件内容的操作详解

本文是关于如何用Python os.path.walk方法遍历搜索文件目录内容的操作详解的文章,python 代码中用os.path.walk函数这个python模块的方法来遍历文件,python列出文件夹下的所有文件并找到自己想要的内容。

文中使用到了Python os模块和Python sys模块,这两个模块具体的使用方法请参考玩蛇网相关文章阅读。

Python os.path.walk方法遍历文件搜索内容方法代码如下:

import os, sys

#代码中需要用到的方法模块导入

listonly = False

skipexts = ['.gif', '.exe', '.pyc', '.o', '.a','.dll','.lib','.pdb','.mdb'] # ignore binary files

def visitfile(fname, searchKey):

global fcount, vcount

try:

if not listonly:

if os.path.splitext(fname)[1] in skipexts:

pass

elif open(fname).read().find(searchKey) != -1:

print'%s has %s' % (fname, searchKey)

fcount += 1

except: pass

vcount += 1

#www.iplaypy.com

def visitor(args, directoryName,filesInDirectory):

for fname in filesInDirectory:

fpath = os.path.join(directoryName, fname)

if not os.path.isdir(fpath):

visitfile(fpath,args)

def searcher(startdir, searchkey):

global fcount, vcount

fcount = vcount = 0

os.path.walk(startdir, visitor, searchkey)

if __name__ == '__main__':

root=raw_input("type root directory:")

key=raw_input("type key:")

searcher(root,key)

print 'Found in %d files, visited %d' % (fcount, vcount)

如何用Python os.path.walk方法遍历搜索文件内容的操作详解,文章所用到的模块方法相关文章推荐:

Python OS模块;

Python sys模块;

Python import语句导入模块语法;

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/code/c2667.html

相关文章 Recommend

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值