python文件路径过滤器_在Python中的过滤器目录

该博客介绍如何使用Python遍历指定目录,计算包含`.py`和`.txt`文件的总数,并查找包含特定字符串(如'import sys')的文件,将这些文件名写入到'found.txt'中。提供了详细的代码实现过程。
摘要由CSDN通过智能技术生成

I am trying to get filtered list of all Text and Python file, like below

from walkdir import filtered_walk, dir_paths, all_paths, file_paths

vdir=raw_input ("enter director :")

files = file_paths(filtered_walk(vdir, depth=0,included_files=['*.py', '*.txt']))

I want to:

know the total number of files found in given directory

I have tried options like : Number_of_files= len (files) or for n in files n=n+1 but all are failing as "files" is something called "generator" Object which I searched on python docs but couldn't make use of it

I also want to find a string e.g. "import sys" in the list of files found in above and store the file names having my search string in new file called "found.txt"

解决方案

I believe this does what you want, if I misunderstood your specification, please let me know after you give this a test. I've hardcoded the directory searchdir, so you'll have to prompt for it.

import os

searchdir = r'C:\blabla'

searchstring = 'import sys'

def found_in_file(fname, searchstring):

with open(fname) as infp:

for line in infp:

if searchstring in line:

return True

return False

with open('found.txt', 'w') as outfp:

count = 0

search_count = 0

for root, dirs, files in os.walk(searchdir):

for name in files:

(base, ext) = os.path.splitext(name)

if ext in ('.txt', '.py'):

count += 1

full_name = os.path.join(root, name)

if found_in_file(full_name, searchstring):

outfp.write(full_name + '\n')

search_count += 1

print 'total number of files found %d' % count

print 'number of files with search string %d' % search_count

Using with to open the file will also close the file automatically for you later.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值