从外部url打开txt文件时出现问题

2024-10-01 15:45:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法从外部URL打开txt文件。 下面的代码在从我的PC读取下载的txt文件时可以正常工作

URL='grst0120.txt'

但是如果我试图从外部站点读取相同的txt文件,如

URL='https://downloads.usda.library.cornell.edu/usda-esmis/files/xg94hp534/0c4841048/8w32rn389/grst0120.txt'

下面的代码从美国农业部网站上打开一个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])

Tags: 文件代码httpsretxturldownloadsline
2条回答

open()不接受URL,而只接受指向本地文件的路径。对于Python3.x,可以使用^{}

import urllib.request

URL = "https://downloads.usda.library.cornell.edu/usda-esmis/files/xg94hp534/0c4841048/8w32rn389/grst0120.txt"

data = urllib.request.urlopen(URL)

for line in data:
    print(line) 

我可以看到的一种方法是使用urllib模块将文本文件下载到一个文件夹中,然后从那里打开它

https://stackabuse.com/download-files-with-python/

urllib的使用在该网站上得到了很好的解释。 虽然我确信,有一种更有效的方法来执行任务,但这可能是一种方法

相关问题 更多 >

    热门问题