I'm using the below code in an attempt to print 8 lines after a string that is found in the file result.txt. The script is definitely finding the string, but the print function returns 8 empty lines after the string is found, rather than the contents of the actual lines.
request = urllib.request.Request(websiteurl)
response = urllib.request.urlopen(request)
data = response.read()
fw = open('result1.txt', 'w')
fw.write(str(data))
fw.close()
with open('result1.txt', 'r') as f:
for line in f:
if 'DeMarco' in line:
for _ in range(8):
print (f.readline())
Your script is working, but you may add the parameter end='' in print function to avoid the automatically added end of line:
print (f.readline(), end='')
Are you sure about your file content? With 4 lines and this content file:
0
a DeMarco z
1
2
3
4
5
6
xDeMarcoPaul
A
B
DeMarco
C
D
E
F
And this script:
with open('result1.txt', 'r') as f:
for line in f:
if 'DeMarco' in line:
for _ in range(4):
print (f.readline(), end='')
I have this output:
1
2
3
4
A
B
DeMarco
C
But if in the 8 following lines, there is also a pattern DeMarco, it will not be detected because f.readline()
moves the cursor.
Just read response result in tuples of lines. Your code should look like this:-
response = urllib.request.urlopen(websiteurl)
data = response.read()
fw = open('result1.txt', 'w')
fw.write(str(data))
fw.close()
lines = tuple(open('result1.txt', 'r'))
for x in lines:
if 'google' in x:
for y in range(8):
print(x)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.