使用pysftp的put_r上传文件时触发Not a directory错误求助
单个文件SFTP上传报错NotADirectoryError的解决思路
问题描述
尝试用pysftp的put_r方法上传单个本地文件到SFTP服务器,持续触发NotADirectoryError错误。传入本地目录路径时代码可正常上传整个目录,但需求是单个文件上传。
相关代码
import os import pysftp 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'
解决思路
put_r是递归上传目录的方法,内部会执行os.chdir(localpath)切换到目标路径,传入单个文件路径时必然触发"不是目录"的错误。- 单个文件上传直接替换为
put方法,核心代码修改如下:
# 若remotepath是远程目录,需拼接文件名形成完整远程路径 sftp.put(localpath, os.path.join(remotepath, local_file)) # 若remotepath已包含完整文件名(如'/remote/path/test_file_sftp.csv'),直接传参即可 # sftp.put(localpath, remotepath)
- 额外注意:确保远程目标目录已存在,若不确定可提前用
sftp.makedirs(remotepath)创建目录,避免上传失败。
内容的提问来源于stack exchange,提问作者GLTCL
相关产品推荐
相关产品推荐

