2016-03-09 145 views
0
for root, dirs, files in os.walk('/path/to/directory'): 
    for file in files: 
     if line in file: 
      if re.match(b'\x64', line): 
       print file 

来如何,当我搜索有其内容中的十六进制字符x64(ASCII d)的文件中,只有包含d印回来,当我在每个搜索在文件内容中是否有行?搜索文件内容

+3

您没有正在搜索文件内容。如果你在那里,必须有一个“开放(文件)”的地方。你只是匹配文件名称,这正是你说你得到的。 – msw

回答

2

file变量file in files实际上是文件的名称,而不是文件的句柄
为了获得文件的句柄,你需要先到open()吧。

import os 
import re 


for root, dirs, files in os.walk('/path/to/directory'): 
    for filename in files: 
     with open(os.path.join(root, filename)) as file: 
      for line in file: 
       if re.match(b'\x64', line): 
        print filename 
+0

可能工作(如果该字符在行首)但不关闭任何文件句柄。 –

+0

@tobias_k更正了! –

+0

谢谢,它正在工作 –