我希望能够通过查找具有特定字符串的行(在我的情况下是错误)来过滤日志文件,然后将包含匹配字符串的行及其后面的一组行写入到新文件中。
我的问题是,对于某些文件来说,它不起作用,当文件中的字符串确实匹配时,它不会返回任何字符串匹配。
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()
问题与文件的创建方式有关 很奇怪 ...
创建一个新文件并将旧文件中的文本复制并粘贴到这个新文件中,代码可以按预期工作。