저는 Python으로 설치 스크립트를 스크립팅하고 있습니다.ftp에서 파일을 다운로드하는 방법은 무엇입니까?
ftp에서 파일을 어떻게 다운로드합니까?
운영 체제 - Windows XP - 차이가있을 경우.
저는 Python으로 설치 스크립트를 스크립팅하고 있습니다.ftp에서 파일을 다운로드하는 방법은 무엇입니까?
ftp에서 파일을 어떻게 다운로드합니까?
운영 체제 - Windows XP - 차이가있을 경우.
다음은 현재 사용중인 코드입니다.
import mimetypes
import os
import urllib2
import urlparse
def filename_from_url(url):
return os.path.basename(urlparse.urlsplit(url)[2])
def download_file(url):
"""Create an urllib2 request and return the request plus some useful info"""
name = filename_from_url(url)
r = urllib2.urlopen(urllib2.Request(url))
info = r.info()
if 'Content-Disposition' in info:
# If the response has Content-Disposition, we take filename from it
name = info['Content-Disposition'].split('filename=')[1]
if name[0] == '"' or name[0] == "'":
name = name[1:-1]
elif r.geturl() != url:
# if we were redirected, take the filename from the final url
name = filename_from_url(r.geturl())
content_type = None
if 'Content-Type' in info:
content_type = info['Content-Type'].split(';')[0]
# Try to guess missing info
if not name and not content_type:
name = 'unknown'
elif not name:
name = 'unknown' + mimetypes.guess_extension(content_type) or ''
elif not content_type:
content_type = mimetypes.guess_type(name)[0]
return r, name, content_type
사용법 :
req, filename, content_type = download_file('http://some.url')
는 그런 다음 파일 - 류의 객체로 req
를 사용하고, 예를 들어 수 shutil.copyfileobj()
을 사용하여 파일 내용을 로컬 파일에 복사하십시오. MIME 유형이 중요하지 않으면 단순히 코드의 해당 부분을 제거하십시오. 당신이 게으른 것 같다 때문에
, 여기에 로컬 파일에 직접 파일을 다운로드 한 코드입니다 :
import shutil
def download_file_locally(url, dest):
req, filename, content_type = download_file(url)
if dest.endswith('/'):
dest = os.path.join(dest, filename)
with open(dest, 'wb') as f:
shutil.copyfileobj(req, f)
req.close()
당신이 끝나는 경로를 지정하는 경우이 방법은 서버가 보낸 파일 이름을 사용 똑똑 슬래시. 그렇지 않으면 지정한 대상이 사용됩니다. 문서에서
사용 ftplib
코드 샘플 :
>>> from ftplib import FTP
>>> ftp = FTP('ftp.cwi.nl') # connect to host, default port
>>> ftp.login() # user anonymous, passwd [email protected]
>>> ftp.retrlines('LIST') # list directory contents
total 24418
drwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 .
dr-xr-srwt 105 ftp-usr pdmaint 1536 Mar 21 14:32 ..
-rw-r--r-- 1 ftp-usr pdmaint 5305 Mar 20 09:48 INDEX
.
.
.
>>> ftp.retrbinary('RETR README', open('README', 'wb').write)
'226 Transfer complete.'
>>> ftp.quit()
from urllib2 import urlopen
req = urlopen('ftp://ftp.gnu.org/README')
그런 다음 저장할 shutil.copyfileobj
을 변수로 파일 내용을로드하거나 함께 다른 작업을 수행 할 req.read()
를 사용하거나 수 내용을 메모리에로드하지 않고 디스크에 저장합니다.
+1. 짧고 달콤하며 일합니다. – noiv
from urllib.request import urlopen
try:
req = urlopen('ftp://ftp.expasy.org/databases/enzyme/enzclass.txt')
except:
print ("Error")
더 쉬운 옵션을 제공 할 수 있습니까? – Zygimantas
심각하게? 한 줄짜리 함수 호출을 복사 & 붙여 넣기를 사용하는 것보다 쉬운 것은 무엇입니까? – ThiefMaster
어디에서 파일 이름을 입력합니까? – Zygimantas