Python pysftp下载失败,并显示"IOError:[Errno 21]是目录". [英] Python pysftp download fails with "IOError: [Errno 21] Is a directory"
问题描述
这是我的示例Python脚本,我想在其中将文件从SFTP服务器下载到本地.
Here is my sample Python script where I want to download a file from SFTP server to my local.
srv = pysftp.Connection(host=host, username=username, password=password, port=port, cnopts=connOption)
with srv.cd(sftppath):
data = srv.listdir()
try:
for infile in data:
print infile
srv.get(infile, destination, preserve_mtime=True)
我可以成功连接,并且列出了文件夹中的所有文件.但是,当我使用srv.get()
将其下载到桌面时,出现以下错误,
I can connect successfully and it lists all files in the folder. But when I use srv.get()
to download to my desktop I get following error,
IOError:[Errno 21]是目录:'/Users/ratha/Desktop'
IOError: [Errno 21] Is a directory: '/Users/ratha/Desktop'
错误堆栈;
Traceback (most recent call last):
File "/Users/ratha/PycharmProjects/SFTPDownloader/handler.py", line 9, in <module>
main()
File "/Users/ratha/PycharmProjects/SFTPDownloader/handler.py", line 5, in main
downloadSFTPFiles()
File "/Users/ratha/PycharmProjects/SFTPDownloader/Utilities/SFTPConnector.py", line 49, in downloadSFTPFiles
srv.get(infile, destination, preserve_mtime=True)
File "/Users/ratha/PycharmProjects/SFTPDownloader/venv/lib/python2.7/site-packages/pysftp/__init__.py", line 249, in get
self._sftp.get(remotepath, localpath, callback=callback)
File "/Users/ratha/PycharmProjects/SFTPDownloader/venv/lib/python2.7/site-packages/paramiko/sftp_client.py", line 801, in get
with open(localpath, "wb") as fl:
IOError: [Errno 21] Is a directory: '/Users/ratha/Desktop'
我在这里做错了什么?
推荐答案
堆栈跟踪实际上非常清晰.只需关注这两行:
The stack trace is actually really clear. Just focus on these two lines:
with open(localpath, "wb") as fl:
IOError: [Errno 21] Is a directory: '/Users/ratha/Desktop'
很显然,pysftp
尝试将/Users/ratha/Desktop
作为文件进行打开以进行二进制写入,但运行不顺利,因为它已经是一个目录了. 文档将对此进行确认:>
Clearly, pysftp
tries to open /Users/ratha/Desktop
as a file for binary write, which didn't go well because that is already, well, a directory. The documentation will confirm this:
localpath (str) –要复制目标的本地路径和文件名.如果未指定,则将文件复制到本地当前工作目录
localpath (str) – the local path and filename to copy, destination. If not specified, file is copied to local current working directory
因此,您需要确定要另存为的文件名,并使用(最佳实践)os.path.join('/Users/ratha/Desktop', filename)
来获取路径和文件名,而不仅仅是路径.
Therefore you need to figure out the file name you want to save as, and use (best practice) os.path.join('/Users/ratha/Desktop', filename)
to get a path and filename, instead of just a path.
这篇关于Python pysftp下载失败,并显示"IOError:[Errno 21]是目录".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!