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. 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?
2 Answers 2
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
return
my_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
How about this:
with open('MyText.txt', 'r') as f:
time = None
for line in f:
if 'Time Taken' in line:
time = line[line.find("#") + 1:].strip()
if 'Sample Text' in line:
print "I have found it"
if time:
print "Time taken:", time
- not sure what that first
f.readline()
was for... - no need to explicitly invoke
f.close()
when usingwith
- find time taken in the first pass through the file instead of resetting the pointer and seeking again
- you could use
find()
to get the substring after the#
andstrip()
to get rid of the extra spaces
-
\$\begingroup\$ Point1 ,Point2 and Point3 are very valid. Thanks for pinting those out. Point 4:
print ' '.join(line.split()) print line[line.find("#") + 1:].strip()
give the following outputTime Taken for writing this# 0 days 0 hrs 0 min 14 sec Time Taken for writing this# 0 days 0 hrs 0 min 14 sec
I prefer first to the second as it looks better formatted. \$\endgroup\$misguided– misguided2013年07月03日 23:08:57 +00:00Commented Jul 3, 2013 at 23:08