我需要帮助编写轻量级 Python (v3.6.4) 脚本来搜索文件和文件夹目录中的单个关键字。目前,我正在使用 Notepad++ 来搜索文件目录,尽管我相信 Python 脚本会更快?
当前脚本:
import os
key = input("Search For?: ")
folder = os.listdir("/")
for line in folder:
if key in line:
print(line)
编辑:我使用 Notepad++ 来运行这些搜索查询。
我想搜索的目录在文件夹中有多个级别的文件。
你真的应该使用grep
(即grep -Ril "keyword" /
),或者,如果在Windows中,findstr
(findstr /I /M /C:"keyword" /S \*
),但如果你坚持通过Python的做它,你需要使用os.walk()
到步行通过根目录递归,然后打开每一个找到的文件和叠代找到,如果它包含您想要的关键字,例如:
import os
keyword = input("Search For?: ") # ask the user for keyword, use raw_input() on Python 2.x
root_dir = "/" # path to the root directory to search
for root, dirs, files in os.walk(root_dir, onerror=None): # walk the root dir
for filename in files: # iterate over the files in the current dir
file_path = os.path.join(root, filename) # build the file path
try:
with open(file_path, "rb") as f: # open the file for reading
# read the file line by line
for line in f: # use: for i, line in enumerate(f) if you need line numbers
try:
line = line.decode("utf-8") # try to decode the contents to utf-8
except ValueError: # decoding failed, skip the line
continue
if keyword in line: # if the keyword exists on the current line...
print(file_path) # print the file path
break # no need to iterate over the rest of the file
except (IOError, OSError): # ignore read and permission errors
pass
测试:我刚刚测试了它,PyEnum_Type
通过在运行 CPython 3.5.1 的本地系统上克隆到(因此)的CPython 源代码搜索,结果如预期:F:\.tmp\cpython-master
root_dir = r"F:\.tmp\cpython-master"
搜索?:PyEnum_Type F:\.tmp\cpython-master\Include\enumobject.h F:\.tmp\cpython-master\Objects\enumobject.c F:\.tmp\cpython-master\Objects\object.c F:\.tmp\cpython-master\PC\python3.def F:\.tmp\cpython-master\Python\bltinmodule.c
如果它没有产生任何结果,您很可能设置了错误的路径,或者您正在搜索定义下的文件中不存在的内容root_dir
(或者您的用户无权访问它们)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句