Python Forum
[SOLVED] Find last occurence of pattern in text file?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[SOLVED] Find last occurence of pattern in text file?
#1
Thumbs Up 
Hello,

In a multiline text file, I need to find the last occurence of a pattern, ie. the Python equivalent of "tail".

None of the following works:

import re

INPUTFILE = "log.txt" 

with open(INPUTFILE) as reader:
    content = reader.read()

#====================
#very slow, even on 130KB file
p = re.compile("(?s:.*)^Some pattern.+$")
m = p.search(content)
if m.group(0):
	print(m.group(0))

#====================
#IndexError: list index out of range
p = re.compile("^Some pattern.+$")
m = p.findall(content)[-1]
if m.group(0):
	print(m.group(0))

#====================
#AttributeError: 'NoneType' object has no attribute 'group'
p = re.compile("^Some pattern.+$")
for line in content:
	m = p.search(line)
	if m.group(0):
		print(m.group(0))

#====================
#AttributeError: 'str' object has no attribute 'readlines'
for line in content.readlines():
	m = p.search(line)
	if m.group(0):
		print(m.group(0))
Anyone knows?

Thank you.
Reply


Messages In This Thread
[SOLVED] Find last occurence of pattern in text file? - by Winfried - Aug-13-2021, 02:03 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question [SOLVED] [Beautiful Soup] Replace tag.string from another file? Winfried 2 604 May-01-2025, 03:43 PM
Last Post: Winfried
  [SOLVED] [Linux] Write file and change owner? Winfried 6 1,820 Oct-17-2024, 01:15 AM
Last Post: Winfried
  [solved] how to delete the 10 first lines of an ascii file paul18fr 7 2,129 Aug-07-2024, 08:18 PM
Last Post: Gribouillis
Question [SOLVED] Correct way to convert file from cp-1252 to utf-8? Winfried 8 11,260 Feb-29-2024, 12:30 AM
Last Post: Winfried
  FileNotFoundError: [WinError 2] The system cannot find the file specified NewBiee 2 3,208 Jul-31-2023, 11:42 AM
Last Post: deanhystad
  Loop through json file and reset values [SOLVED] AlphaInc 2 5,873 Apr-06-2023, 11:15 AM
Last Post: AlphaInc
  Cannot find py credentials file standenman 5 3,627 Feb-25-2023, 08:30 PM
Last Post: Jeff900
  selenium can't find a file in my desk ? SouAmego22 0 1,355 Feb-14-2023, 03:21 PM
Last Post: SouAmego22
  Pypdf2 will not find text standenman 2 1,945 Feb-03-2023, 10:52 PM
Last Post: standenman
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 2,149 Dec-15-2022, 04:32 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020