2014-08-28 105 views
0

我有了几行文本文件,让说:如何检查,看看是否在内容文件存在于目录中的文件中的内容

cat 
dog 
rabbit 

我想遍历目录来检查是否有任何文本文件包含上述列表中的项目。

我尝试了许多不同的方法。我不想发布任何内容,因为我想要一个新的开始......思路清晰。我对下面的代码进行了处理,以至于我甚至不知道发生了什么,并且我完全失去了意义。 :(

#! /usr/bin/python 

''' 
The purpose of this program 
is to search the OS file system 
in order to find a txt file that contain the nagios host entries 
''' 

import os 

host_list = open('/path/path/list', 'r') 

host = host_list.read() 
##for host in host_remove.read(): 

host_list.close() 
#print host 

for root, dirs, files in os.walk("/path/path/somefolder/"): 
    for file in files: 
     if file.endswith(".txt"): 

      check_file = os.path.join(root, file) 
      #print check_file 


      if host.find(check_file): #in check_file: 

       print host.find(check_file)      
       #print host+" is found in "+check_file 
       #print os.path.join(root, file) 
      else: 
       break 
+2

你的问题的第二部分完全是题外话。我删除它。 – MattDMo 2014-08-28 17:52:34

+0

您可以分享您迄今为止的尝试吗? – dano 2014-08-28 18:46:41

+0

第二个问题是公平的吗?但任何谁 – user3655020 2014-08-28 18:51:20

回答

2

the shell command的模拟:

$ find /path/somefolder/ -name \*.txt -type f -exec grep -wFf /path/list {} + 

在Python中:

#!/usr/bin/env python 
import os 
import re 
import sys 

def files_with_matched_lines(topdir, matched): 
    for root, dirs, files in os.walk(topdir, topdown=True): 
     dirs[:] = [d for d in dirs if not d.startswith('.')] # skip "hidden" dirs 
     for filename in files: 
      if filename.endswith(".txt"): 
       path = os.path.join(root, filename) 
       try: 
        with open(path) as file: 
         for line in file: 
          if matched(line): 
           yield path 
           break 
       except EnvironmentError as e: 
        print >>sys.stderr, e 

with open('/path/list') as file: 
    hosts = file.read().splitlines() 
matched = re.compile(r"\b(?:%s)\b" % "|".join(map(re.escape, hosts))).search 
for path in files_with_matched_lines("/path/somefolder/", matched): 
    print path 
+0

J.F. Sebastian,当我从一个特定的目录搜索时,你的代码工作的很好。但是,如果我在根级搜索,您的程序将不可避免地尝试打开它无权访问的文件。我们如何为此创建一个例外? for files_with_matched_lines(“/”,matched): 文件“/Users/dmartin/scripts/python/host_removal/naghstlctv3.py”,第11行,位于files_with_matched_lines ,开放(路径)为文件: IOError:[ Errno 13] Permission denied:'/private/etc/racoon/psk.txt' – user3655020 2014-08-31 03:48:02

+0

我忘了添加。你的代码完全pythonic,因为它在unix和windows上运行。我只是试了一下。我只需稍作修改就可以在打开文件的两个地方接受原始字符串(r)。唯一需要做的就是添加一个异常,以便在程序无法访问该文件时尝试搜索。 – user3655020 2014-08-31 04:18:54

+0

@ user3655020:我已经更新了代码,以便在读取文件 – jfs 2014-08-31 07:36:14

2

Python是方式,方法矫枉过正这个任务只需使用grep:。

$ grep -wFf list_of_needles.txt some_target.txt 

如果你确实需要使用Python,裹grep呼叫subprocess或类似

+0

好吧,我很感激它可能会杀死。我其实有bash脚本,可以满足我在peaces中需要的功能。我选择使用python。主要是为了帮助学习这门语言。我讨厌从书本上练习。我发现必要性是发明之母。当我编码实际需要的东西时,我倾向于学习得很好。我本来可以在python中使用OS命令,但我想成为pythonic .....这实际上给我带来了另一个问题,我希望它不是脱离主题....看到这是python的过度杀手..你认为python用于什么? – user3655020 2014-08-28 19:10:31

+0

'find/path/path/somefolder/-name \ * .txt -exec grep -xFf hosts/path/path/list {} +' – jfs 2014-08-28 19:11:17

+0

是的,这就是它在bash中完成的一种方式....怎么做我在没有使用bash的情况下在python中执行它? – user3655020 2014-08-28 19:16:50

0

我对J.F. Sebastian提供的algorytms做了一些小的修改。 更改将要求用户输入。它也将运行在没有问题的窗口上。

#!/usr/bin/env python 
import os 
import re 
import sys 

contents = raw_input("Please provide the full path and file name that contains the items you would like to search for \n") 
print "\n" 
print "\n" 
direct = raw_input("Please provide the directory you would like to search. \ 
Use C:/, if you want to search the root directory on a windows machine\n") 

def files_with_matched_lines(topdir, matched): 
    for root, dirs, files in os.walk(topdir, topdown=True): 
     dirs[:] = [d for d in dirs if not d.startswith('.')] # skip "hidden" dirs 
     for filename in files: 
      if filename.endswith(".txt"): 
       path = os.path.join(root, filename) 
       try: 
        with open(path) as file: 
         for line in file: 
          if matched(line): 
           yield path 
           break 
       except EnvironmentError as e: 
        print >>sys.stderr, e 

with open(contents) as file: 
    hosts = file.read().splitlines() 
matched = re.compile(r"\b(?:%s)\b" % "|".join(map(re.escape, hosts))).search 
for path in files_with_matched_lines(direct, matched): 
    print path