Windows下用Python ftplib访问FTP目录遇socket.gaierror错误求助
Fixing the
socket.gaierror When Using Python's ftplib Let's break down what's going wrong here and fix it step by step:
The Root Cause
That socket.gaierror: [Errno 11001] getaddrinfo failed error is happening because you're passing a full path combined with the server address to the FTP constructor. The FTP() class expects only the server's hostname (like ftp5.xyz.eu) as its first argument—not a combined string like ftp5.xyz.eu/foo%20bar. When you do that, Python tries to resolve ftp5.xyz.eu/foo%20bar as a DNS hostname, which doesn't exist, hence the lookup failure.
The Correct Approach
You need to separate connecting to the server from navigating to your target directory. Here's how to do it right:
- Connect to the FTP server first—only use the hostname here.
- Authenticate (if required; skip this for anonymous FTP).
- Navigate to your target directory using the
cwd()method (short for "change working directory"). You don't need to URL-encode spaces—just pass the path as a normal string with spaces. - Run your
dir()command once you're in the right directory.
Working Example Code
from ftplib import FTP # Step 1: Connect to the server (only the hostname here!) ftp = FTP("ftp5.xyz.eu") # Step 2: Log in (use your credentials if needed; anonymous login uses ftp.login()) ftp.login("your_username", "your_password") # Step 3: Navigate to the target directory. You can do this in one go or split it: # Option 1: Single cwd call for the full path ftp.cwd("foo bar/baz") # Option 2: Split into two steps (useful if you want to verify each step) # ftp.cwd("foo bar") # ftp.cwd("baz") # Step 4: Now you can successfully list the directory contents ftp.dir() # Don't forget to close the connection when you're done ftp.quit()
Quick Notes
- If you run into issues with the space in "foo bar", double-check that the directory name on the server exactly matches (most FTP servers are case-sensitive).
- For anonymous FTP, just call
ftp.login()without any arguments.
内容的提问来源于stack exchange,提问作者Voicu Mirel
相关产品推荐
相关产品推荐

