简体   繁体   English

从网站 url 逐行读取和打印文本文件

[英]reading and printing text file from a website url line by line

I have this code here:我在这里有这段代码:

url = requests.get("https://raw.githubusercontent.com/deppokol/testrepo/main/testfile.txt")
File = url.text
for line in File:
    print(line)

The output looks like this: output 看起来像这样:

p
i
l
l
o
w

and so on...等等...

Instead, I want it to look like this:相反,我希望它看起来像这样:

pillow
fire
thumb

and so on...等等...

I know I can add end="" inside of print(line) but I want a variable to be equal to those lines.我知道我可以在 print(line) 中添加 end="" 但我希望变量等于这些行。 For example例如

Word = line

and when you print Word, it should look like this:当你打印 Word 时,它应该是这样的:

pillow
fire
thumb

.text of requests ' response is str , you might use .splitlines for iterating over lines as follows: requests.text的响应是str ,您可以使用.splitlines对行进行迭代,如下所示:

import requests
url = requests.get("https://raw.githubusercontent.com/deppokol/testrepo/main/testfile.txt")
for line in url.text.splitlines():
    print(line)

Note that .splitlines() deals with different newlines , so you can use it without worrying about what newlines exactly are used (using .split("\n") is fine as long are you sure you working with Linux-style newlines)请注意, .splitlines()处理不同的换行符,因此您可以使用它而不必担心确切使用了哪些换行符(只要您确定使用 Linux 样式的换行符,使用.split("\n")就可以了)

you cannot do for line in url.text because url.text is not a IO ( File ).您不能for line in url.text做,因为url.text不是IOFile )。 Instead, you can either print it directly (since \n or the line breaks will automatically print as line breaks) or if you really need to split on new lines, then do for line in url.text.split('\n') .相反,您可以直接打印它(因为\n或换行符将自动打印为换行符),或者如果您确实需要在新行上拆分,则for line in url.text.split('\n') .

import requests
url = requests.get("https://raw.githubusercontent.com/deppokol/testrepo/main/testfile.txt")
for line in url.text.split('\n'):
    print(line)

Edit: You might also want to do .strip() as well to remove extra line breaks.编辑:您可能还想做.strip()以删除额外的换行符。

response is a str object which you need to split() first as:响应是一个str object 您需要先将其split()为:

import requests
url = requests.get("https://raw.githubusercontent.com/deppokol/testrepo/main/testfile.txt")
file = url.text.split()
for line in file:
    print(line)

You can also use split("\n") :您也可以使用split("\n")

import requests

for l in requests.get("https://raw.githubusercontent.com/deppokol/testrepo/main/testfile.txt").text.split("\n"):
  print(l)

Demo演示

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

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