【问题标题】:Reading all files from ftp folders and subfolders in python从python中的ftp文件夹和子文件夹中读取所有文件
【发布时间】:2015-01-19 01:34:12
【问题描述】:

我想从内存中 ftp 文件夹的所有文件夹和子文件夹中读取所有图像文件 (*.jpg),但不一定要下载它们。文件夹结构的深度不同,我需要的文件可以在主文件夹或任何子文件夹中。

我尝试在循环中使用 nlst,但我只是得到一个文件列表并且无法单独读取 jpg 文件。一旦我读取了一个文件,我计划使用 opencv 对该文件进行一些处理,并在一个数组中提取特定信息,然后转到下一个文件。

这是我的代码:我还不能浏览子文件夹。

log = []
file_list = []
for name in ftp.nlst():
        print "listing: " + name
        ftp.cwd(name)
        ftp.retrlines('LIST',callback=log.append)
        #lines = lines.split("\n") # This should split the string into an array of lines
        #filename_index = len(lines[0]) - 1
        files = (line.rsplit(None, 1)[1] for line in log)
        for file in files:
            if file.split('.')[-1] == "jpg":            
            # whatever
                    file_list.append(file)
        ftp.cwd('../')

感谢任何帮助。

【问题讨论】:

    标签: python ftplib


    【解决方案1】:

    使用os导入并在listdir函数中传递ftp文件夹或子文件夹路径。

    import os
    
    for file in os.listdir('<INSERT FTP FULL PATH>'):
        if file.endswith(".jpg"):
            print(file)
            ...
            or do other python processing
    

    【讨论】:

    • 在 os.listdir 中使用 FTP 完整路径时出现错误。
    • 很抱歉给您带来了困惑。您实际上必须在单引号之间插入 FTP 路径。让我编辑我的答案。
    • 我这里一定是做错了什么。我试过了,但仍然得到一个 WindowsError 作为 WindowsError: [Error 123] The filename, directory name, or volume label syntax is wrong: 'ftp.xyz.com/abc%20Creative/Site%20Specific%20Creative*.*'
    • 那么,您的 FTP 路径在您的操作系统 (os) 上不像虚拟目录那样是可访问的路径。您将不得不使用 ftplib 模块。看到这个SO answer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2011-07-29
    相关资源
    最近更新 更多