2011-04-26 71 views

回答

18

事情是这样的:

import os 
directory = os.path.join("c:\\","path") 
for root,dirs,files in os.walk(directory): 
    for file in files: 
     if file.endswith(".log") or file.endswith(".txt"): 
      f=open(file, 'r') 
      for line in f: 
       if userstring in line: 
       print "file: " + os.path.join(root,file)    
       break 
      f.close() 
+0

在windows中,walk方法就像os.walk('c:/ Python27')或者其他的东西?谢谢! – suffa 2011-04-26 14:50:41

+0

@ user706808请参阅我的编辑。 – ghostdog74 2011-04-26 14:54:33

+0

请注意'str.endswith(suffix [,start [,end]])'可以为后缀取一个元组。过多的“或”比较会导致麻烦。 – 2016-10-18 19:29:34

2

做到这一点在Python?否则,只需grep -l "string" *.txt *.log将工作。

+0

lbrahim是的,我需要在Python中做到这一点。谢谢(你的)信息! – suffa 2011-04-26 14:52:12

+2

@Andre Caron看起来像一个合理的问题......当你听到文字时你一定很明亮! ...你是谁来确定它听起来像什么?小伙子们,我很久以前就读完了......这是一种自我利益的爱好。没有什么更好的与你的时间做,然后带来消极。像你这样的人...... – suffa 2011-04-26 15:23:53

3

他要了一个扁平的readdir,而不是递归文件树的步行路程。 os.listdir()完成这项工作。

相关问题