2010-07-04 4 views
4

C#에서이 작업을 수행 할 수 있으며 코드가 꽤 오래되었습니다.목록에서 파일을 다운로드하지 않은 경우

누군가 파이썬을 통해 어떻게 이루어질 수 있는지 알 수 있다면 멋지겠습니까?

의사 코드는 다음과 같습니다

url: www.example.com/somefolder/filename1.pdf 

1. load file into an array (file contains a url on each line) 
2. if file e.g. filename1.pdf doesn't exist, download file 

스크립트는 다음과 레이아웃에있을 수 있습니다 :

/python-downloader/ 
/python-downloader/dl.py 
/python-downloader/urls.txt 
/python-downloader/downloaded/filename1.pdf 

답변

11

이 트릭을 할해야한다, 나는 urls.txt 파일 URL 만 포함되어 있다고 가정하더라도. 접두사가 아닌 url:입니다.

import os 
import urllib 

DOWNLOADS_DIR = '/python-downloader/downloaded' 

# For every line in the file 
for url in open('urls.txt'): 
    # Split on the rightmost/and take everything on the right side of that 
    name = url.rsplit('/', 1)[-1] 

    # Combine the name and the downloads directory to get the local filename 
    filename = os.path.join(DOWNLOADS_DIR, name) 

    # Download the file if it does not exist 
    if not os.path.isfile(filename): 
     urllib.urlretrieve(url, filename) 
+0

놀랍도록 간결합니다. 나는 모든 과대 광고가 무엇인지에 관해 알기를 간청하고있다! 고마워! – Blankman

+0

'/'로 분리하는 대신 os.path.basename (url)을 사용하십시오. – TravisThomas

2

그것은 파이썬으로 적은 코드, 당신은이 같은 것을 사용할 수 있습니다

여기
import urllib2 
improt os 

url="http://.../" 
# Translate url into a filename 
filename = url.split('/')[-1] 

if not os.path.exists(filename) 
    outfile = open(filename, "w") 
    outfile.write(urllib2.urlopen(url).read()) 
    outfile.close() 
4

파이썬 3.3 WoLpH의 스크립트를 약간 수정 된 버전입니다.

#!/usr/bin/python3.3 
import os.path 
import urllib.request 

links = open('links.txt', 'r') 
for link in links: 
    link = link.strip() 
    name = link.rsplit('/', 1)[-1] 
    filename = os.path.join('downloads', name) 

    if not os.path.isfile(filename): 
     print('Downloading: ' + filename) 
     try: 
      urllib.request.urlretrieve(link, filename) 
     except Exception as inst: 
      print(inst) 
      print(' Encountered unknown error. Continuing.') 
관련 문제