简体   繁体   English

使用python从FTP下载特定文件

[英]Download specific file from FTP using python

quick and simple: 快速简单:

I have the following function, works well if i specify the file name. 我具有以下功能,如果我指定文件名,效果很好。

import os
import ftplib

def ftpcon(self, host, port, login, pwd, path):

    ftp = ftplib.FTP()
    ftp.connect(host, port, 20)
    try:

        ftp.login(login, pwd)
        ftp.cwd(path)

        for files in ftp.nlst():

            if files.endswith('.doc') or files.endswith('.DOC'):

                ftp.retrbinary('RETR ' + files, open(file, 'wb').write)
                print files

But when i use the for loop with ftp.nlst() to try to match an specific type of file, i receive the error: 但是,当我在ftp.nlst()中使用for循环来尝试匹配特定类型的文件时,我收到错误消息:

coercing to Unicode: need string or buffer, type found 强制转换为Unicode:需要字符串或缓冲区,找到类型

Since im not sure if this is the best way to do it, what could the "correct" way to download a file ? 由于我不确定这是否是最好的方法,因此下载文件的“正确”方法是什么?

Maybe try: 也许尝试:

from ftplib import FTP

server = FTP("ip/serveradress")
server.login("user", "password")

server.retrlines("LIST") # Will show a FTP content list.
server.cwd("Name_Of_Folder_in_FTP_to_browse_to") # browse to folder containing your file for DL

then: 然后:

server.sendcmd("TYPE i") # ready for file transfer
server.retrbinary("RETR %s"%("FILENAME+EXT to DL"), open("DESTINATIONPATH+EXT", "wb").write) # this will transfer the selected file...to selected path/file

believe this is as correct as serves.. 相信这和服务一样正确。

u can set server.set_debuglevel(0) to (1) or (2) for more detailed description while logged in to server. 您可以在登录服务器时将server.set_debuglevel(0)设置为(1)或(2)以获得更详细的描述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM