[英]Search multiple files in folder and sub folders python
Trying to search for a search word inside multiple files in current folder and sub folders and print them to a file.尝试在当前文件夹和子文件夹的多个文件中搜索搜索词并将它们打印到文件中。
i can print out the files in terminal using os.walk.我可以使用 os.walk 打印出终端中的文件。 But i want to search all the files in the folders for a specific word
但我想在文件夹中的所有文件中搜索特定单词
import glob, os
output_file = 'Funkar.txt'
search_str = '"Prefix"'
for root, dirs, files in os.walk("."):
for file in files:
if file.endswith(".wpp"):
print(os.path.join(root, file))
with open(os.path.join(root, file), 'r') as fr, open (output_file,'a', encoding='utf-8') as fw:
for i,line in enumerate(fr):
if line.find(search_str) != -1:
fw.write(line)
now gives me现在给我
in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 12: character maps to <undefined>
Search and print:搜索和打印:
import os
def search( folder, word ):
for root, dirs, files in os.walk(folder):
path = root.split(os.sep)
for filename in files:
fullname = os.path.join(root, filename)
if open( fullname ).read().find( word ) != -1:
print( fullname )
search( "FolderName", 'any text')
Search and backup searched lines:搜索和备份搜索到的行:
import os
def search( folder, word, bfile ):
for root, dirs, files in os.walk(folder):
path = root.split(os.sep)
for filename in files:
fullname = os.path.join(root, filename)
if open( fullname ).read().find( word ) != -1:
print( fullname )
blines = [x for x in open(fullname).readlines() if x.find(word) != -1]
open( bfile, 'a' ).writelines(blines)
search( "FolderName", 'any text', 'backup-lines.file')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.