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?

3 Answers 3

5
with open(file_path) as infile:
    for line in infile:
        if 'sum' in line:
            print line.split()[0] # Assuming space separated
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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]

3 Comments

if 'sum' in Line: ... will work as well. Also, according to the documentation, open is more preferable than file.
great thanks alot. If I want to print the nest value next to aaaa how would I print the values for 0 and 1. print Line.split()[0,1]??? I get an error with this
Line.split()[1] should do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.