如何将csv文件从pysftp下载到本地机器上?无法将其保存到本地路径,或将其加载到

2024-09-20 03:57:59 发布

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

尝试连接到sftp,下载cvs,对文件进行一些操作并将其保存为csv

我知道代码在sftp中导航到文件夹的部分都是正确的。我认为它是在下载文件,因为代码运行需要一些时间,而且下载的文件很大。但我还不能执行任何命令来打印文件,以确保它确实已被下载。不确定get函数中的第二个参数是否应该是在本地计算机中保存文件的目标。你知道吗

import pysftp

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None   

myHostname = 'host.com'
myUsername = 'username'
myPassword = 'pass'

server = pysftp.Connection(host=myHostname, username=myUsername, password=myPassword, cnopts=cnopts)
server.cwd('/targetFolder/')
server.get('/targetFolder/file.csv','C:\\')

这是我得到的错误:

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-74-0925a6d2adf3> in <module>
     10 server = pysftp.Connection(host=myHostname, username=myUsername, password=myPassword, cnopts=cnopts)
     11 server.cwd('/targetFolder/')
---> 12 server.get('/targetFolder/file.csv','C:\\')

C:\Users\rschuetz\Documents\Winpython\WPy64-3720\python-3.7.2.amd64\lib\site-packages\pysftp\__init__.py in get(self, remotepath, localpath, callback, preserve_mtime)
    247             sftpattrs = self._sftp.stat(remotepath)
    248 
--> 249         self._sftp.get(remotepath, localpath, callback=callback)
    250         if preserve_mtime:
    251             os.utime(localpath, (sftpattrs.st_atime, sftpattrs.st_mtime))

C:\Users\rschuetz\Documents\Winpython\WPy64-3720\python-3.7.2.amd64\lib\site-packages\paramiko\sftp_client.py in get(self, remotepath, localpath, callback)
    799             Added the ``callback`` param
    800         """
--> 801         with open(localpath, "wb") as fl:
    802             size = self.getfo(remotepath, fl, callback)
    803         s = os.stat(localpath)

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\'

Tags: 文件csvselfhostgetservercallbacksftp
2条回答

似乎代码要求的是本地路径的文件名,而不是目录名,因此我认为这将起作用:

server.get('/targetFolder/file.csv','C:/file.csv')

我怀疑下一行中的问题,并将第二个参数作为原始字符串传递进行了更正。你知道吗

server.get('/targetFolder/file.csv',r'C:\\')

相关问题 更多 >