【发布时间】:2020-01-14 17:00:55
【问题描述】:
我无法从外部 URL 打开 txt 文件。 从我的 PC 读取下载的 txt 文件时,下面的代码可以正常工作,例如
URL='grst0120.txt'
但如果我尝试从像
这样的外部站点读取相同的 txt 文件,它就不起作用URL='https://downloads.usda.library.cornell.edu/usda-esmis/files/xg94hp534/0c4841048/8w32rn389/grst0120.txt'
下面的代码从 USDA 网站打开一个 txt 文件,并打印所有带有单词 "December" 的行。从我的 PC 打开下载的 txt 文件时,该代码工作正常,但我需要另一种方法从 Internet 打开相同的文件。我很感激任何帮助。
代码...
import re
URL = "https://downloads.usda.library.cornell.edu/usda-esmis/files/xg94hp534/0c4841048/8w32rn389/grst0120.txt"
# The code fails with this external URL but it works fine if I download the txt file and
# I change the URL pointing to my PC location, like, URL = "grst0120.txt".
Stocks = []
LineNum = 0
pattern = re.compile("December", re.IGNORECASE)
with open (URL, 'rt') as myfile:
for line in myfile:
LineNum += 1
if pattern.search(line) != None:
Stocks.append((LineNum, line.rstrip('\n')))
for Stocks_found in Stocks:
print("Line " + str(Stocks_found[0]) + ": " + Stocks_found[1])
【问题讨论】:
-
open()不接受外部 URL。 -
听说过 urllib 吗?