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
  • 28,332
  • 6
  • 65
  • 82
Trying_hard
  • 8,931
  • 29
  • 62
  • 85

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
  • 28,332
  • 6
  • 65
  • 82
Kien Truong
  • 11,179
  • 2
  • 30
  • 36
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
  • 155,636
  • 47
  • 315
  • 299
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,413
  • 12
  • 15