Reputation: 9501
I have a LARGE text file that I am needing to pull several values from. the text file has alot of info I don't need. Is there a way I can serach for a specific term that is in a line and return the first value in that line. Please example below
text
text text
text
text text text
text text
aaaaa text sum
text
text
text
I need to search for sum and return the value of aaaaa
Is there a way that I can do this?
Upvotes: 0
Views: 360
Reputation: 1423
Are you looking for something like this?
for Line in file("Text.txt", "r"):
if Line.find("sum") >= 0:
print Line.split()[0]
Line.split()
will split the line up into words, and then you can select with an index which starts from 0, i.e. to select the 2nd word use Line.split()[1]
Upvotes: 0
Reputation: 11381
with open(file_path) as infile:
for line in infile:
if 'sum' in line:
print line.split()[0] # Assuming space separated
Upvotes: 5
Reputation: 164357
If the text file is indeed big, you can use mmap — Memory-mapped file support as found in here: Python Random Access File.
Upvotes: 2