本文介绍了在Python中的过滤器目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我试图从walkdir导入filtered_walk,dir_paths中获取所有Text和Python文件的过滤列表,如下所示: all_paths,file_paths vdir = raw_input(enter director:) files = file_paths(filtered_walk(vdir,depth = 0,included_files = ['*。py','* .txt '])) 我想: 知道在给定目录中找到的文件总数 我已经尝试了如下选项:Number_of_files = len(files)对于文件n = n + 1中的n,但所有都失败,因为文件是所谓的生成器我在python文档搜索,但无法使用它的对象$ / b $ b 我也想查找一个字符串eg import sys在上面找到的文件列表中,并将具有我的搜索字符串的文件名存储在名为found.txt的新文件中。 解决方案我相信这是做你想做的,如果我误解了你的规范,请给我一个测试后告诉我。我已经对 searchdir 目录进行了硬编码,因此您必须提示。 $ b searchdir = r'C:\ blabla' searchstring ='import sys' $ b $ def search_in_file(fname,searchstring) :打开(fname)作为infp:在infp中的行:如果searchstring在行中: return True return False 在open.bat('found.txt','w')作为outfp: count = 0 search_count = 0 for root,dirs,os.walk中的文件(searchdir):$ (base,ext)= os.path.splitext(name)如果在('.txt','.py' + = 1 $ b $ full_name = os.path.join(root,name) if found_in_file(full_name,searchstring): outfp.write(full_name +'\\\' ) search_count + = 1 print'total numb呃找到的文件%d'%count print'搜索字符串%d'的文件数%search_count 使用和来打开文件也会在稍后自动关闭文件。 I am trying to get filtered list of all Text and Python file, like belowfrom walkdir import filtered_walk, dir_paths, all_paths, file_pathsvdir=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 directoryI 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 itI 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 ossearchdir = 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 Falsewith 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 += 1print 'total number of files found %d' % countprint 'number of files with search string %d' % search_countUsing with to open the file will also close the file automatically for you later. 这篇关于在Python中的过滤器目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-19 12:32