【问题标题】:Python download files from FTP ignoring the missing onesPython 从 FTP 下载文件忽略丢失的文件
【发布时间】:2017-11-23 10:05:19
【问题描述】:

我在 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 循环中创建一个 if 但我无法让它工作,有人可以给我一些想法或提示吗?

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    熟悉try-except blocks 来处理这个问题:

    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.")
    

    【讨论】:

    • 谢谢!!工作完美,我会阅读异常处理文档,感谢您的信息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 2021-10-10
    • 1970-01-01
    • 2014-04-08
    • 2014-08-05
    • 1970-01-01
    • 2012-07-30
    相关资源
    最近更新 更多