问题
I am using python in Windows with ftplib to access a folder at ftp5.xyz.eu.
The folder is 'baz' in ftp5.xyz.eu in the folder 'foo bar'. So : ftp5.xyz.eu/foo bar/baz
I connect successfully at ftp5.xyz.eu but when i write the whole path to the folder it gives me an error:
from ftplib import FTP
#domain name or server ip:
ftp = FTP('ftp5.xyz.eu/foo%20bar')
...
ftp.dir()
error gived below:
File "C:\Users\mirel.voicu\AppData\Local\Programs\Python\Python37\lib\ftplib.py", line 117, in __init__
self.connect(host)
File "C:\Users\mirel.voicu\AppData\Local\Programs\Python\Python37\lib\ftplib.py", line 152, in connect
source_address=self.source_address)
File "C:\Users\mirel.voicu\AppData\Local\Programs\Python\Python37\lib\socket.py", line 707, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
File "C:\Users\mirel.voicu\AppData\Local\Programs\Python\Python37\lib\socket.py", line 748, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed
回答1:
This has nothing to do with the space. The first argument of FTP constructor is host – a hostname or an IP address – not an URL.
So it should be:
ftp = FTP('ftp5.xyz.eu')
If you want to list files in foo bar subfolder, either do:
ftp.cwd('foo bar')
ftp.dir()
or
ftp.dir('foo bar')
回答2:
The error message is Python's slightly obtuse way of saying "there is no server with that name"; and indeed, the server name here is not valid. You are passing 'ftp5.xyz.eu/foo%20bar' where you should be passing in just 'ftp5.xyz.eu'.
FTP traditionally does not use URL addresses, and Python's ftplib has no support for parsing them. You will need to pick apart the URL using, oh, I guess urllib, and take it from there.
from ftplib import FTP
from urllib.parse import urlparse
parsed = urlparse('ftp://ftp5.xyz.eu/foo%20bar')
ftp = FTP(parsed.netloc)
ftp.login()
ftp.cwd(parsed.path)
ftp.dir()
The parsed parsed.path still uses %20 where probably the FTP server expects a literal space; maybe also do URL decoding (urllib.parse.unquote or maybe urlllib.parse.unquote_plus).
来源:https://stackoverflow.com/questions/64427208/access-ftp-url-with-ftplib