2016-03-23 43 views
1

由于在Python(2.7),我真的是一个新手在寻找下一个建议:由Python的链接下载文件存储在CSV

我有分隔的一列逗号存储HTTP链接csv文件。

http://example.com/file.pdf, 
http://example.com/file.xls, 
http://example.com/file.xlsx, 
http://example.com/file.doc, 

主要目的是循环所有这些链接并通过它们下载文件的原始扩展名和名称。

所以我的搜索结果,并帮助这里给我下一个脚本:

import urllib2 
import pandas as pd 

links = pd.read_csv('links.csv', sep=',', header =(0)) 

url = links     # I know this part wrong by don`n know how to do right 

user_agent = 'Mozilla 5.0 (Windows 7; Win64; x64)' 

file_name = "tessst"   # here the files name by how to get their original names 

u = urllib2.Request(url, headers = {'User-Agent' : user_agent}) 
req = urllib2.urlopen(u) 
f = open(file_name, 'wb') 
f.write(req.read()) 

f.close() 

请任何帮助

P不是肯定大熊猫 - 也许CSV更好?

+0

那么http://stackoverflow.com/a/19602990/3014866? –

回答

1

如果我可以假设你的CSV文件只有一列,包含链接,那么这将工作。

import csv, sys 
import requests 
import urllib2 
import os 

filename = 'test.csv' 
with open(filename, 'rb') as f: 
    reader = csv.reader(f) 
    try: 
     for row in reader: 
      if 'http' in row[0]: 
       #print row 
       rev = row[0][::-1] 
       i = rev.index('/') 
       tmp = rev[0:i] 
       #print tmp[::-1] 
       rq = urllib2.Request(row[0]) 
       res = urllib2.urlopen(rq) 
       if not os.path.exists("./"+tmp[::-1]):     
        pdf = open("./" + tmp[::-1], 'wb') 
        pdf.write(res.read()) 
        pdf.close() 
       else: 
        print "file: ", tmp[::-1], "already exist" 
    except csv.Error as e: 
     sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) 
+0

一般而言,它在一些更改(添加标题后)后工作,但它重写了文件 –

+0

很喜欢它的使用。我已经更改了代码,现在只有在以前没有下载文件时才会下载代码。 ###和平 –

+0

谢谢你的答案 - 但主要目的 - 让所有文件 - 不是一个 - 仍然未得到 –