按关键字过滤文件行不适用于某些文件

问题描述 投票:0回答:1

我希望能够通过查找具有特定字符串的行(在我的情况下是错误)来过滤日志文件,然后将包含匹配字符串的行及其后面的一组行写入到新文件中。

我的问题是,对于某些文件来说,它不起作用,当文件中的字符串确实匹配时,它不会返回任何字符串匹配。

我对可能的原因有两个想法

  1. 我正在通过 vs code 运行 python 脚本(我不知道 vs code 是否在运行 python 脚本时做了奇怪的事情)
  2. 我没有使过滤功能不区分大小写,我是Python新手,但我认为我这样做是正确的。
import os

inputFileQuestion = input("What is the file name? ").strip()
inputFile = os.path.join(os.getcwd(), inputFileQuestion)

if not os.path.isfile(inputFile):
        print(f"Error: no such file '{inputFile}'")
        exit()

def returnText(line, numberOfLines, topAndBottom):
    result = []
    with open(inputFile, 'r') as file:
        lines = file.readlines()
        start_index = max(0, line - numberOfLines)
        end_index = min(len(lines), line + numberOfLines + 1)
        if topAndBottom:
            result = lines[start_index:end_index]
        else:
            result = lines[line:end_index]
    return result

def readFile(searchString):
    arrayOfStrings = []
    with open(inputFile, 'r') as file:
        lines = file.readlines()
        for i, line in enumerate(lines):
            if searchString.lower() in line.lower():
                print(f"Match found on line {i+1}: {line.strip()}") # Debug statement
                text = returnText(i, 2, True) # Zero-index adjustment
                arrayOfStrings.extend(text)
    return arrayOfStrings

def writeFile(filename, textArray):
    with open(filename, 'w') as file:
        file.write('\n'.join(textArray))
        print(f"Written to file {filename}") # Debug statement

def main():
    searchString = input("What is the text you are searching for? ")
    fileName = input("What is the output filename you would like? ")
    
    arrayOfText = readFile(searchString)
    if arrayOfText:
        writeFile(fileName, arrayOfText)
        print("File successfully written!")
    else:
        print("No matches found in the input file.")

main()
python file filter filtering
1个回答
0
投票

问题与文件的创建方式有关 很奇怪 ...

创建一个新文件并将旧文件中的文本复制并粘贴到这个新文件中,代码可以按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.