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

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:

  1. Connect to the FTP server first—only use the hostname here.
  2. Authenticate (if required; skip this for anonymous FTP).
  3. 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.
  4. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 16:22:36