简体   繁体   English

如何打开当前目录中的所有.txt和.log文件,搜索并打印找到搜索的文件

[英]How to open all .txt and .log files in the current directory, search, and print the file the search was found

I'm trying to search for a string in all text and log files in the current directory. 我正在尝试在当前目录中的所有文本和日志文件中搜索字符串。 And if it finds a match, print the text or log file where the match was found. 如果找到匹配项,则打印找到匹配项的文本或日志文件。 Is this possible, and how can I manipulate the code below to accomplish this task? 这是可能的,我如何操纵下面的代码来完成这项任务?

  fiLe = open(logfile, "r")
  userString = raw_input("Enter a string name to search: ")
  for line in fiLe.readlines():
      if userString in line:
         print line

Something like this: 像这样的东西:

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()

He asked for a flat readdir, not for a recursive file tree walk. 他要求一个平坦的readdir,而不是一个递归的文件树步行。 os.listdir() does the job. os.listdir()完成这项工作。

Do you have to do it in Python? 必须用Python做吗? Otherwise, simply grep -l "string" *.txt *.log would work. 否则,只需grep -l "string" *.txt *.log就行了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在目录中的所有文本文件中搜索字符串并将找到的结果放在 Python 的文本文件中 - How do I search all text files in directory for a string and place the found result in a text file in Python 尝试遍历目录中的文本文件,打开每个文件,搜索内容,如果找到匹配项则打印 - Trying to loop through text files in a directory, open each, search contents, and print if a match is found 如何在Python / Flask中打开和搜索大型txt文件 - How to open and search large txt files in Python/ flask 如何在python中打开文件,忽略大小写搜索单词,找到单词打印成功? - How to open a file in python, search for a word ignoring case, print success of word is found? 在Python目录中搜索.txt,.scv文件 - Search for .txt, .scv files in directory in Python Python:在当前目录及其所有父目录中搜索文件 - Python: search for a file in current directory and all it's parents 如何在python3中从txt文件中搜索和打印一行? - How to search and print a line from txt file in python3? 使用glob.glob从当前目录向下递归搜索* .txt文件 - Use glob.glob to search recursively for *.txt files, from current directory down 在txt文件中搜索字符串/否则打印不存在 - Search txt file for string / else print not present 如何相对于日志文件中的搜索读取Python的前几行? - How to read previous lines in Python relative to a search found in the log file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM