简体   繁体   中英

Reading all files from ftp folders and subfolders in python

I want to read all the image files (*.jpg) from all the folders and subfolders of a ftp folder in memory, but not necessarily download them. The folder structure varies in depth and the files I need can be in the main folder or in any subfolder.

I tried using nlst in a loop, but I am just getting a listing of files and haven't been able to read the jpg files individually. Once I read one file, I plan to do some processing on the file using opencv and extract specific information in an array and move on to the next file.

Here is my code: I haven't been able to navigate through subfolders yet.

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('../')

Any help is appreciated.

Use the os import and pass the ftp folder or subfolder path in the listdir function.

import os

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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