“[WinError 6]句柄无效”,使用Urllib

2024-10-02 12:26:46 发布

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

import urllib.request

def Download(url, file_name):
    urllib.request.urlretrieve(url, file_name)

f = open("links.txt", "r")
lines = f.readlines()

for line in lines:
    for x in range (1, 5):
        filenaame = x


        cut_string = line.split('?$')
        new_string = cut_string[0]
        numerator = new_string.split('/1/')
        separator = ''

        link = (separator.join(numerator[0] + "/{}/".format(x) + numerator[1]))

        file_name = link.split('/{}/'.format(x))
        file_name = file_name[1]
        file_name = file_name.split('.')
        file_name = (separator.join(file_name[0] + "{}".format(filenaame)))
        filenaame =+ 1

        print("Downloading: {}".format(file_name))
        Download(link, filenaame)

错误:

^{pr2}$

我在google上搜索了很多关于这个的东西,结果我发现这个人在使用subprocess模块,而我没有,这使得它更加困难。在

代码是用来下载图像的。它确实成功地下载了第一个,然后崩溃了。有人知道是什么导致了这个错误吗?我还是个初学者。在


Tags: nameformaturlforstringrequestdownloadlink
2条回答

在这条线上

urllib.request.urlretrieve(url, file_name)

这里文件名应该是一个字符串,所以在调用下载(link,filenaame)将integer filenaame设为string try。在

^{pr2}$

下载图像的工作示例

^{3}$

你将你的计数器作为第二个参数传递。最后,该函数将其作为文件名将下载的数据复制到。在

通过传递一个整数,可以将“传递低级文件描述符”启用到^{}

file is either a string or bytes object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped.

但文件描述符不存在(幸运的是!)在

让我们在这里重现这个问题:

>>> open(4,"rb")
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
OSError: [Errno 9] Bad file descriptor

解决办法显然是:

^{pr2}$

(我建议您将filenaame计数器重命名为更有意义的,这样可以避免类似的错误)

相关问题 更多 >

    热门问题