我有一个csv文件中的数字列表,如下所示:
1 2 3 4 5还有一个名为类似这些数字的ftp服务器:
1.jpg 2.jpg 4.jpg 5.jpg(3.jpg缺失)
如果文件名在该csv列表中,我想要下载FTP的所有文件。
在我的代码上,我可以成功下载文件但是当它试图在FTP上下载丢失的文件时程序崩溃:
urllib2.URLError: <urlopen error ftp error: [Errno ftp error] 550 Can't change directory to 3.jpg: No such file or directory>Python代码:
#!/usr/bin/python # -*- coding: utf-8 -*- import urllib2, shutil import pandas as pd import numpy as np from ftplib import FTP FTP_server = 'ftp://user:pass@server.com/' ftp = FTP_server+'the/path/to/files/' class Test: def Get(self): data = pd.read_csv('test.csv',encoding='utf-8',delimiter=';') #data['REF'].replace('', np.nan, inplace=True) #data.dropna(subset=['REF'], inplace=True) data['REF'] = data['REF'].astype(int) new_data = data['REF'] for ref in new_data: file = str(ref)+str('.jpg') ftpfile = urllib2.urlopen(ftp+file) localfile = open(file, 'wb') shutil.copyfileobj(ftpfile, localfile) Try = Test() Try.Get()我试图做一个如果在for循环内,但我不能得到它的工作,有人可以给我一些想法或提示plz?
I've a list of numbers on csv file like this:
1 2 3 4 5And an ftp server with files named like those numbers:
1.jpg 2.jpg 4.jpg 5.jpg( 3.jpg is missing )
I want to download all the files of the FTP if the filename is on that csv list.
On my code i can successfully download the files but when it tryes to download a missing file on FTP the program crashes with:
urllib2.URLError: <urlopen error ftp error: [Errno ftp error] 550 Can't change directory to 3.jpg: No such file or directory>Python code:
#!/usr/bin/python # -*- coding: utf-8 -*- import urllib2, shutil import pandas as pd import numpy as np from ftplib import FTP FTP_server = 'ftp://user:pass@server.com/' ftp = FTP_server+'the/path/to/files/' class Test: def Get(self): data = pd.read_csv('test.csv',encoding='utf-8',delimiter=';') #data['REF'].replace('', np.nan, inplace=True) #data.dropna(subset=['REF'], inplace=True) data['REF'] = data['REF'].astype(int) new_data = data['REF'] for ref in new_data: file = str(ref)+str('.jpg') ftpfile = urllib2.urlopen(ftp+file) localfile = open(file, 'wb') shutil.copyfileobj(ftpfile, localfile) Try = Test() Try.Get()I'm trying to make an if inside the for loop but i can't get it working, someone can give me some idea or tip plz?
最满意答案
熟悉try-except块来处理这个问题:
for ref in new_data: try: file = str(ref)+str('.jpg') ftpfile = urllib2.urlopen(ftp+file) localfile = open(file, 'wb') shutil.copyfileobj(ftpfile, localfile) except urllib2.URLError: print("-I- Skipping",file," - doesn't exist.")Get acquainted with try-except blocks to handle this:
for ref in new_data: try: file = str(ref)+str('.jpg') ftpfile = urllib2.urlopen(ftp+file) localfile = open(file, 'wb') shutil.copyfileobj(ftpfile, localfile) except urllib2.URLError: print("-I- Skipping",file," - doesn't exist.")更多推荐
发布评论