使用pysftp上传文件时出现FileNotFoundError的问题求助
Let's break down what's happening here and fix this step by step:
1. First, Verify the Local File Actually Exists
When you pass ds as the local path, the script recognizes it's a directory—but when you add /test.txt, it throws a "No such file" error. This usually means one of two things:
- The file
test.txtdoesn't actually exist inside thedsdirectory relative to where you're running the script. - Your script's working directory isn't what you expect, so the relative path
ds/test.txtpoints to a non-existent location.
To confirm this, add a quick check using Python's os module before attempting the upload:
import os localpath = 'ds/test.txt' print(f"Current working directory: {os.getcwd()}") print(f"Does file exist? {os.path.exists(localpath)}") print(f"Absolute path to file: {os.path.abspath(localpath)}")
If the output shows the file doesn't exist, either create the file in the correct location or adjust the localpath to use an absolute path (e.g., /home/youruser/ds/test.txt instead of the relative one).
2. Fix the Remote Path Handling
Your current remotepath is set to /var/sftp/uploads, which is a directory. When using pysftp.Connection.put(), if you specify a directory as the remote path, you need to make sure the server expects this behavior—or explicitly include the filename in the remote path to avoid ambiguity.
Many SFTP servers require you to specify the full path to the target file, not just the directory. Update your remotepath to include the filename:
remotepath = '/var/sftp/uploads/test.txt'
This tells pysftp exactly where to place the file, instead of trying to infer it (which can fail depending on server configuration).
3. Optional: Add Better Error Handling
Instead of just re-raising the generic exception, you can catch more specific errors to get clearer insights:
import pysftp as sftp import os def sftp_send(): localpath = 'ds/test.txt' # Check local file first if not os.path.isfile(localpath): raise FileNotFoundError(f"Local file not found: {localpath}") try: with sftp.Connection(host='****', username='****', password='****') as s: # Verify remote directory exists (optional but helpful) if not s.exists('/var/sftp/uploads'): raise FileNotFoundError("Remote directory /var/sftp/uploads does not exist") remotepath = '/var/sftp/uploads/test.txt' s.put(localpath, remotepath) print("File uploaded successfully!") except sftp.SSHException as e: print(f"SFTP connection error: {e}") except Exception as e: print(f"Unexpected error: {e}") sftp_send()
Using a with statement also ensures the connection is closed automatically, even if an error occurs.
4. Double-Check Permissions
Even though you mentioned checking permissions, it's worth verifying:
- Your local user has read access to
ds/test.txt - The remote SFTP user has write access to
/var/sftp/uploads - The remote directory
/var/sftp/uploadsactually exists (the code above includes a check for this)
内容的提问来源于stack exchange,提问作者DariusFontaine

