Download files from a list if not already downloaded

后端 未结 3 449
离开以前
离开以前 2020-12-31 15:02

I can do this in c#, and the code is pretty long.

Would be cool if someone can show me how this would be done via python.

Pseudo code is:

u         


        
相关标签:
3条回答
  • 2020-12-31 15:41

    It's less code in Python, you could use something like this:

    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()
    
    0 讨论(0)
  • 2020-12-31 15:48

    Here is a slightly modified version of WoLpH's script for Python 3.3.

    #!/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.')
    
    0 讨论(0)
  • 2020-12-31 15:50

    This should do the trick, although I assume that the urls.txt file only contains the url. Not the url: prefix.

    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 讨论(0)
提交回复
热议问题