![](/img/trans.png)
[英]How do I search all text files in directory for a string and place the found result in a text file in Python
[英]How to open all .txt and .log files in the current directory, search, and print the file the search was found
我正在嘗試在當前目錄中的所有文本和日志文件中搜索字符串。 如果找到匹配項,則打印找到匹配項的文本或日志文件。 這是可能的,我如何操縱下面的代碼來完成這項任務?
fiLe = open(logfile, "r")
userString = raw_input("Enter a string name to search: ")
for line in fiLe.readlines():
if userString in line:
print line
像這樣的東西:
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()
他要求一個平坦的readdir,而不是一個遞歸的文件樹步行。 os.listdir()完成這項工作。
你必須用Python做嗎? 否則,只需grep -l "string" *.txt *.log
就行了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.