使用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
withstatement 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
相关产品推荐
相关产品推荐

