Python脚本查找包含文本字符串的文件

时间:2019-06-18 10:44:30

标签: python

用于查找包含文本字符串的文件的Python脚本

我想找到一个包含特定字符串的文本文件。

以下未找到匹配的文件名和匹配的行号。

import os

search_path = "C:\\Users\\xx\\Desktop\\text_file\\" #folder to search
file_type = ".txt" #filetype to search
search_str = " INTERIM BILL-SUMMARY" #string to search

if not (search_path.endswith("/") or search_path.endswith("\\") ): # Append a directory separator if not already present
        search_path = search_path + "/"                                                         
if not os.path.exists(search_path):  # If path does not exist, set search path to current directory
        search_path ="."
for fname in os.listdir(path=search_path): # Repeat for each file in the directory 
   if fname.endswith(file_type):  # Apply file type filter  
        fo = open(search_path + fname) # Open file for reading
        line = fo.readline() # Read the first line from the file
        line_no = 1 # Initialize counter for line number
        while line != '' :   # Loop until EOF
                index = line.find(search_str) # Search for string in line
                if ( index != -1) :
                    print(fname, "[", line_no, ",", index, "] ", line, sep="")           
                line = fo.readline()  # Read next line
                line_no += 1 # Increment line counter
        fo.close() # Close the files

2 个答案:

答案 0 :(得分:1)

请您尝试一下,告诉我它是否适合您?

import os

search_path = "C:\\Users\\xx\\Desktop\\text_file\\" #folder to search
file_type = ".txt" #filetype to search
search_str = "INTERIM BILL-SUMMARY" #string to search

if not (search_path.endswith("/") or search_path.endswith("\\") ): # Append a directory separator if not already present
        search_path = search_path + "/"                                                         
if not os.path.exists(search_path):  # If path does not exist, set search path to current directory
        search_path ="."
for fname in os.listdir(path=search_path): # Repeat for each file in the directory 
   if fname.endswith(file_type):  # Apply file type filter  
        with open(search_path + fname) as f: # Open file for reading
            for line_no, line in enumerate(f):
                if search_str in line:
                    print(fname, "[", line_no, ",", line.find(search_str), "] ", line, sep="")

答案 1 :(得分:0)

我只是偶然发现了这个帖子:),并修改了一些行以便更好地处理和csv输出!

import os
import csv

search_path = input("Enter directory path to search : ")
file_type = input("File Type : ")
search_str = input("Enter the search string : ")

if not (search_path.endswith("/") or search_path.endswith("\\") ): # Append a directory separator if not already present
        search_path = search_path + "/"                                                         
if not os.path.exists(search_path):  # If path does not exist, set search path to current directory
        search_path ="."
for fname in os.listdir(path=search_path): # Repeat for each file in the directory 
   if fname.endswith(file_type):  # Apply file type filter  
        with open(search_path + fname,encoding="utf-8") as f: # Open file for reading
            with open('output.csv', 'a+') as output:
            #csvwriter = csv.writer(csvfile)
                for line_no, line in enumerate(f):
                    if search_str in line:
                        output.write("".join(map(str, [line])))
                        print(fname, "[", line_no, ",", line.find(search_str), "] ", line, sep="")