我试图使用python 3从网络上读取内容,然后逐行打印所有行。

到目前为止,我看到的最好的方法是使用urllib.request并执行以下操作:

import urllib.request
url_target = urllib.request.urlopen("http://stackoverflow.com")
tmp_copy_string = url_target.read().decode("utf8")
file = "file"
for word in tmp_copy_string:
        print(word)


我以为这个代码可以逐字打印-它不起作用...

问题不仅在于它不逐字打印,而是逐字符打印。

有一种逐行打印的好方法吗?

无需使用其他库。

最佳答案

您可以按\n对其进行分割:

import urllib.request

url_target = urllib.request.urlopen("http://stackoverflow.com")
tmp_copy_string = url_target.read().decode("utf8").split('\n')    #split string on newline

for line in tmp_copy_string:
        print(line)


这将逐行打印代码

09-10 03:02
查看更多