MyText.txt This is line 1This is line 2 Time Taken for writing this#      0 days 0 hrs 1 min 5 secNothing ImportantSample TextObjectiveTo 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 Codewith 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.  I want to know 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 suggest alternative/faster approaches for this?
Text file reading and printing data
python;beginner;file;python 2.7
as you say, it does look like this code is doing exactly what you want. But it also looks like you are repeating yourself in a couple of places.If it was me, I would prefer to loop through the file only once and check for both Sample Text and Time Taken at the same time, and then only print out if the sample text is there:def my_read(my_text):    time_taken, sample_text = False, False    with open(my_text) as f:        for i in f:            time_taken = ' '.join(i.split()) if 'Time Taken' in i else time_taken            sample_text = 'I have found it!' if 'Sample Text' in i else sample_text    # now, if sample text was found, print out    if sample_text:        print sample_text        print time_taken    returnmy_read('MyText.txt')By testing for both, you avoid having to use f.seek(0) and start looping through the file again. Of course, this is based on the sample input above - and assumes that there isn't multiple lines with 'Time taken' or 'Sample Text' in them. Hope this helps