You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pysftp的get_r()复制远程目录时遇文件未找到错误

Fixing "No such file or directory" Error with pysftp get_r

It looks like the error is popping up because the local directory you’re trying to download into doesn’t exist—and pysftp’s get_r method doesn’t automatically create missing local directories. Let’s fix this step by step:

Step 1: Create the Local Directory First

Add code to generate the local directory (and any missing parent folders) before calling get_r. Use Python’s built-in os.makedirs function for this:

import os
import pysftp

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

# Use a raw string for Windows paths to avoid escape character headaches
local_path = r'E:\New Folder\FTP Download Folder'
# Create the local directory (and parents) if it doesn't exist
os.makedirs(local_path, exist_ok=True)

# Use a 'with' statement to ensure proper connection cleanup
with pysftp.Connection("10.2.2.99", username="user", password="password", cnopts=cnopts) as p:
    remote_path = '/cradius-data/files/webapps/vcm/somedirectory'
    p.get_r(remotedir=remote_path, localdir=local_path)

Key Improvements:

  • Raw string for Windows path: The r'...' syntax eliminates the need for double backslashes and prevents accidental escape sequence errors.
  • Automatic directory creation: os.makedirs(..., exist_ok=True) creates the folder (and any missing parent folders) if it doesn’t exist, without throwing an error if it’s already there.
  • Proper connection management: The with statement ensures the SFTP connection is closed automatically after the download finishes, which is a best practice for resource handling.

Step 2: Double-Check the Remote Path

Just to be thorough, confirm the remote directory actually exists. You can add a quick check to rule out issues on the server side:

with pysftp.Connection("10.2.2.99", username="user", password="password", cnopts=cnopts) as p:
    remote_path = '/cradius-data/files/webapps/vcm/somedirectory'
    if p.isdir(remote_path):
        print("Remote directory found—starting download...")
        p.get_r(remotedir=remote_path, localdir=local_path)
    else:
        print(f"Error: Remote directory {remote_path} doesn't exist")

This will help you confirm whether the problem is with the local or remote path.

内容的提问来源于stack exchange,提问作者Syed Saad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:07:13