Python“IOError:[Errno 21]是一个目录:'/home/thomasshera/Pictures/Star Wars'”

2024-04-27 18:30:57 发布

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

注意:“代码”的第一部分不是代码,而是来自终端的错误信息,SE让我这样格式化。

使用Python 2.7.6的Linux机器

我有一个自动下载器,它应该可以获取剪贴板的内容(这个工作)并下载它们(这不工作)。以下是错误消息:

Traceback (most recent call last):

File "/home/thomasshera/Create polynomial from random sequence.py", line 6, in <module>

urllib.urlretrieve(text_in_clipboard, "/home/thomasshera/Pictures/Star Wars")
File "/usr/lib/python2.7/urllib.py", line 94, in urlretrieve

return _urlopener.retrieve(url, filename, reporthook, data)
File "/usr/lib/python2.7/urllib.py", line 244, in retrieve
tfp = open(filename, 'wb')
IOError: [Errno 21] Is a directory: '/home/thomasshera/Pictures/Star Wars'

代码如下:

import Tkinter
import urllib
root = Tkinter.Tk()
root.withdraw() # Hide the main window (optional)
text_in_clipboard = root.clipboard_get()
urllib.urlretrieve(text_in_clipboard, "/home/thomasshera/Pictures/Star Wars")

使用Python shell修复这个问题很简单,除了我的程序中没有第94行之外——这个shell不知怎么错了?


Tags: 代码textinpyhomelinerooturllib
3条回答

首先,您看到的错误与脚本的第94行无关,而是在urllib.py模块中。

其次,问题是如何使用urlretrieve方法。它接受一个URL和一个文件名。但您使用的是目录的路径,而不是文件。然后urllib告诉你我刚才说的:

IOError: [Errno 21] Is a directory: '/home/thomasshera/Pictures/Star Wars'

请仔细阅读urllib docs

urlretrieve的第二个参数应该是文件的路径,而不是目录。

urllib.urlretrieve(url[, filename[, reporthook[, data]]])

Copy a network object denoted by a URL to a local file, if necessary.

你可以这样处理:

urllib.urlretrieve(text_in_clipboard, "/home/thomasshera/Pictures/Star Wars/download.temp")

错误不会出现在代码中,而是出现在您使用的库中—所以您为什么会看到文件/usr/lib/python2.7/urllib.py的第94行。但原因在你的密码里。urllib.urlretrieve将文件名(而不是文件夹名)作为其第二个参数。(在回溯中,我们看到它被传递给期望文件名的函数open)。这将起作用:

urllib.urlretrieve(text_in_clipboard, "/home/thomasshera/Pictures/Star Wars/data.txt")

相关问题 更多 >