[英]Python3- print (readline()) returning empty lines
I'm using the below code in an attempt to print 8 lines after a string that is found in the file result.txt. 我正在使用以下代码,尝试在文件result.txt中找到的字符串后打印8行。 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.
该脚本肯定是在查找字符串,但是在找到字符串之后,print函数将返回8个空行,而不是实际行的内容。
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: 您的脚本正在运行,但是您可以在打印功能中添加参数end =“''以避免自动添加行尾:
print (f.readline(), end='')
Are you sure about your file content? 您确定文件内容吗? With 4 lines and this content file:
有4行和此内容文件:
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. 但是,如果在接下来的8行中还有一个模式DeMarco,则不会检测到它,因为
f.readline()
移动了光标。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.