Using Python's ftplib to get a directory listing, portably

前端 未结 7 598
盖世英雄少女心
盖世英雄少女心 2020-12-04 16:37

You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is:

# File: ftplib-example-1.py

import ftplib

f         


        
7条回答
  •  伪装坚强ぢ
    2020-12-04 17:05

    The reliable/standardized way to parse FTP directory listing is by using MLSD command, which by now should be supported by all recent/decent FTP servers.

    import ftplib
    f = ftplib.FTP()
    f.connect("localhost")
    f.login()
    ls = []
    f.retrlines('MLSD', ls.append)
    for entry in ls:
        print entry
    

    The code above will print:

    modify=20110723201710;perm=el;size=4096;type=dir;unique=807g4e5a5; tests
    modify=20111206092323;perm=el;size=4096;type=dir;unique=807g1008e0; .xchat2
    modify=20111022125631;perm=el;size=4096;type=dir;unique=807g10001a; .gconfd
    modify=20110808185618;perm=el;size=4096;type=dir;unique=807g160f9a; .skychart
    ...
    

    Starting from python 3.3, ftplib will provide a specific method to do this:

    • http://bugs.python.org/issue11072
    • http://hg.python.org/cpython/file/67053b135ed9/Lib/ftplib.py#l535

提交回复
热议问题