Reputation: 17
I'm trying to write a program on python on mac, that allows users to search a database. Im having trouble to open,find or read the text file that is attached.
I have used:
import os
with open('a3-example-data.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()
and
import os
file = open("/Users/moniv/Downloads/a3-example-data(2).txt", "r" "utf8")
But keep getting an error message. Please help me :(
Upvotes: 0
Views: 3465
Reputation: 24812
your code is flawed in many parts, and my guess is that the error comes when you're getting back to the main iteration, whereas you seeked back to 0
, making the main iteration unsynced.
# you do not need the os module in your code. Useless import
import os
with open('a3-example-data.txt', 'r') as f:
### the f.readline() is only making you skip the first line.
### Are you doing it on purpose?
f.readline()
for line in f:
if 'Sample Text' in line:
print "I have found it"
### seeking back to zero,
f.seek(0)
### skipping a line
f.readline()
### iterating over the file again,
### while shadowing the current iteration
for line in f:
if 'Time Taken' in line:
print line
print ' '.join(line.split()) # why are you joining what you just split?
### and returning to the main iteration which will get broken
### because of the seek(0) within
### does not make much sense.
### you're using the context manager, so once you exit the `with` block, the file is closed
### no need to double close it!
f.close()
so without understanding what you aim to do, here's my take on your algorithm:
import os
with open('a3-example-data.txt', 'r') as f:
f.readline()
for line in f:
if 'Sample Text' in line:
print "I have found it"
break
f.seek(0)
f.readline()
for line in f:
if 'Time Taken' in line:
print line
Upvotes: 3