0

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?

Rik Poggi
  • 26,862
  • 6
  • 63
  • 81
Trying_hard
  • 8,103
  • 25
  • 57
  • 81

3 Answers3

5
with open(file_path) as infile:
    for line in infile:
        if 'sum' in line:
            print line.split()[0] # Assuming space separated
Rik Poggi
  • 26,862
  • 6
  • 63
  • 81
Kien Truong
  • 10,866
  • 2
  • 28
  • 34
2

If the text file is indeed big, you can use mmap — Memory-mapped file support as found in here: Python Random Access File.

Community
  • 1
  • 1
Nitzan Tomer
  • 139,150
  • 41
  • 299
  • 282
0

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]

Ben Russell
  • 1,373
  • 11
  • 15