python - 从 FTP 站点下载名称中包含特定单词的文件

标签 python ftp

你能告诉我我在这里做错了什么吗...我是Python新手...连接后我可以获取FTP特定目录中的文件列表,但出于对BigBang的热爱..它没有下载任何文件。我需要下载以特定名称字符串开头的文件:

from ftplib import FTP_TLS
import fnmatch
import os

ftps = FTP_TLS('myftp_site.com')
ftps.login('userxx', 'pwxx')
ftps.prot_p()
ftps.cwd('Inbox')

print("File list:")

list_of_files = ftps.retrlines("LIST")
dest_dir = "C:\DownloadingDirectory"

for name in list_of_files:
    if fnmatch.fnmatch(name,"StartingFileName*"):
        with open(os.path.join(dest_dir, name), "wb") as f:
            ftps.retrbinary("RETR {}".format(name), f.write)

ftps.quit()

    enter code here

最佳答案

您在获取文件列表时遇到问题。 LIST 返回一个长格式列表,其中包含文件属性,例如

-rw-------   1 td       dialout       543 Apr  3 20:18 .bash_history

使用NLST获取简短列表。另外,retrlines() 函数有点奇怪。它为收到的每一行(默认为打印)调用回调。该命令仅返回状态字符串。您可以添加自己的回调来填充列表,或使用 .nlst() 命令来获取列表。

from ftplib import FTP_TLS
import fnmatch
import os

ftps = FTP_TLS('myftp_site.com')
ftps.login('userxx', 'pwxx')
ftps.prot_p()
ftps.cwd('Inbox')

print("File list:")

list_of_files = []
ftps.retrlines("NLST", list_of_files.append)
# ...or use the existing helper
# list_of_files = ftps.nlst()

dest_dir = "C:\DownloadingDirectory"

for name in list_of_files:
    if fnmatch.fnmatch(name,"StartingFileName*"):
        with open(os.path.join(dest_dir, name), "wb") as f:
            ftps.retrbinary("RETR {}".format(name), f.write)

ftps.quit()

关于python - 从 FTP 站点下载名称中包含特定单词的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43549331/

相关文章:

Python ftplib 被动连接配置错误

python - Django "detail": "Method\"GET\"not allowed." (one to many relationship)

python - 计算 12 个月内还清余额所需支付的最低金额的算法

python - 如何使用 lambda 按字典中元组的值排序?

PHP ftp_put() - "Cannot STOR."

在 Windows 上使用 lftp 进行 git ftp 推送

python - Salesforce 批量 API : InvalidSessionId (Unable to find session id) when executed on Google App Engine

python - 在 Python 中通过没有 Content-Disposition 的 POST 发送文件

ftp - apache VFS2 uriStyle - 根绝对路径以双斜杠结尾

ftp - 如何在亚马逊AWS上使用FTP