简体   繁体   English

如何逐行打印在线txt文件?

[英]How to print the online txt file line by line?

My codes are listed as following:我的代码如下:

import urllib.request, urllib.parse, urllib.error

headers = {'User-Agent':
                       '''Mozilla/5.0 (Windows NT 10.0; Win64; x64) 
                       AppleWebKit/537.36 (KHTML, like Gecko) 
                       Chrome/79.0.3945.117 Safari/537.36'''}

url = 'https://www.py4e.com/code3/mbox.txt'

req = urllib.request.Request(url, headers=headers)

fname = urllib.request.urlopen(req).read().decode()

for line in fname:
    print(line)

The output is not line by line, but characters?输出不是一行一行的,而是字符? How can I print the file line by line?如何逐行打印文件? Thanks a lot!非常感谢!

Try using split by newline for your string.尝试对字符串使用按换行符拆分。

for line in fname.split('\n'):
    print(line)

Your read() is reading the text into a string.您的read()正在将文本读入字符串。

import urllib.request, urllib.parse, urllib.error

headers = {'User-Agent':
                       '''Mozilla/5.0 (Windows NT 10.0; Win64; x64) 
                       AppleWebKit/537.36 (KHTML, like Gecko) 
                       Chrome/79.0.3945.117 Safari/537.36'''}

url = 'https://www.py4e.com/code3/mbox.txt'

req = urllib.request.Request(url, headers=headers)

fname = urllib.request.urlopen(req)
count = 0
for line in fname:
    count += 1
    print(count)
    print(line.decode())

Which Yields:哪个产量:

1
From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008

2
Return-Path: <postmaster@collab.sakaiproject.org>

3
Received: from murder (mail.umich.edu [141.211.14.90])

4
by frankenstein.mail.umich.edu (Cyrus v2.3.8) with LMTPA;

5     
Sat, 05 Jan 2008 09:14:16 -0500

6
X-Sieve: CMU Sieve 2.3

7
Received: from murder ([unix socket])

8
by mail.umich.edu (Cyrus v2.2.12) with LMTPA;

9
Sat, 05 Jan 2008 09:14:16 -0500

10
Received: from holes.mr.itd.umich.edu (holes.mr.itd.umich.edu [141.211.14.79])
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM