使用 put_r 的 Python pysftp 上传失败,并显示"不是目录"



我正试图将文件从本地复制到SFTP,但不知怎的,我一直陷入一些我无法修复的错误。我在下面附上了我从现在开始写的代码,作为例子,我在这里发现了Stack Overflow。

local_dir = '/local/dir'
local_file = 'test_file_sftp.csv'
localpath = os.path.join(local_dir, local_file)
remotepath = '/remote/path/'
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection(host='xx.xx.xx.xx',
username='some_name',
private_key='key',
cnopts=cnopts) as sftp:

sftp.put_r(localpath, remotepath)
print('Upload finished')

这是我至今无法解决的主要错误:

NotADirectoryError                        Traceback (most recent call last)
Input In [40], in <cell line: 12>()
11 #set connection and put file into sftp
12 with pysftp.Connection(host=host, username=username, private_key=private_key, cnopts=cnopts) as sftp:
---> 14     sftp.put_r(localpath, remotepath)
15     print('- Upload finished!')
File /opt/anaconda3/envs/sky_roi/lib/python3.10/site-packages/pysftp/__init__.py:427, in Connection.put_r(self, localpath, remotepath, confirm, preserve_mtime)
425 wtcb = WTCallbacks()
426 cur_local_dir = os.getcwd()
--> 427 os.chdir(localpath)
428 walktree('.', wtcb.file_cb, wtcb.dir_cb, wtcb.unk_cb)
429 # restore local directory
NotADirectoryError: [Errno 20] Not a directory: '/Users/xyz/aaa/ab/cd/ef/test_file_sftp.csv'

我对psftp和SFTP是新手,所以任何形式的提示都将非常感激。

如果我从目录字符串localpath中删除文件,代码可以工作,但它只是上传整个文件夹(显然!)而不是我想要的单个文件。对此有什么建议吗?也许我错过了一些非常基本的东西,我没有注意到它

Connection.put_r用于上传文件夹。您正在上传文件,所以使用Connection.put。尽管它需要remotepath参数中的远程文件路径。所以你需要添加文件名:

local_dir = '/local/dir'
filename = 'test_file_sftp.csv'
localpath = os.path.join(local_dir, filename)
remote_dir = '/remote/path/'
remotepath = remote_dir + filename
sftp.put_r(local, remotepath)

指出:

  • ftp是一个没有维护的项目。你最好使用Paramiko: pysftp vs. Paramiko
  • 不要设置cnopts.hostkeys = None,除非你不关心安全。关于正确的解决方案,请参见使用pysftp验证主机密钥。

如图所示,要合并路径"/local/dir/"文件" test_file_sft"你不需要"/">

如果你写"/test_file_sft"看起来这个文件在"/"

尝试测试您的文件是否存在于该目录中:

#list the files in the path of the local_dir you provided
print(os.listdir(local_dir))
#list files in the current directory you are in:
dir_path = os.getcwd()
print(os.listdir(dir_path))

然后根据

更新路径

最新更新