misguided
misguided

Reputation: 3789

Text File Reading and Printing Data

My Text File MyText.txt

This is line 1
This is line 2 
Time Taken for writing this#      0 days 0 hrs 1 min 5 sec
Nothing Important
Sample Text

Objective

To read the text file and find if "Sample Test is present in the file. If present print the time taken to write the file(which is a value already inside the file)"

My Code

with open('MyText.txt', 'r') as f:
    f.readline()
    for line in f:
        if 'Sample Text' in line:
            print "I have found it"
            f.seek(0)
            f.readline()
            for line in f:
                if 'Time Taken' in line:
                    print line
                    print ' '.join(line.split())
f.close()

The code is working fine. My question is if this code can be made even better . Considering I am new to python, I am sure there would be a better way to code this.Can anyone sugggest alternative/faster approach for this.

Upvotes: 0

Views: 31117

Answers (3)

Ramakanth Reddy
Ramakanth Reddy

Reputation: 139

f = open('sample', 'r') # open file in read mode
data = f.read()      # copy to a string
f.close()               # close the file
print data          # print the data

Upvotes: 4

vidit
vidit

Reputation: 6451

This should work..

with open('MyText.txt', 'r') as f:
  lineArr=f.read().split('\n')
  if 'Sample Text' in lineArr:
    timeTaken = [s for s in lineArr if "Time Taken" in s]
    print timeTaken[0]

Upvotes: 0

mbdavis
mbdavis

Reputation: 4010

Personally I'd get the text out, and then perform operations on it, if the file is fairly small.

f = open("mytext.txt","r")
contents = f.read()
f.close()

for row in contents.split("\n"):
    if "time" in row:
        print(row.split("time")[1])

Upvotes: 2

Related Questions