通过FTP确定列表是否是Python中的目录或文件 [英] Determine if a listing is a directory or file in Python over FTP

查看:245
本文介绍了通过FTP确定列表是否是Python中的目录或文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python有一个标准库模块 ftplib 来运行FTP通信。它有两种获取目录内容列表的方法。其中一个 FTP.nlst()将返回一个目录名称内容列表,其中包含目录名称作为参数。 (如果给定文件名,它将返回文件的名称。)这是列出目录内容的可靠方法,但不会指示列表中的每个项目是文件还是目录。另一种方法是 FTP.dir(),它给出了一个字符串格式的列表,列出了作为参数给出的目录的目录内容(或给定文件的文件属性名称)。



根据上一个关于堆栈溢出的问题,解析 dir()的结果可能很脆弱(不同的服务器可能返回不同的字符串)。不过,我正在寻找一些方法来通过FTP列出其他目录中包含的目录。据我所知,在字符串的权限部分中搜索 d 是我提出的唯一解决方案,但我想我无法保证该权限将显示在不同服务器之间的相同位置。是否有一个更强大的解决方案来通过FTP识别目录?

解决方案

不幸的是,FTP没有命令列出文件夹解析从ftp.dir()获得的结果将是'最好的'。



一个简单的应用程序,假设来自ls(不是windows ftp)的标准结果

  from ftplib import FTP 

ftp = FTP(host,user,passwd)
for r in ftp.dir():
如果r.upper()。startswith('D'):
print r [58:]#起点

标准FTP命令



自定义FTP命令


Python has a standard library module ftplib to run FTP communications. It has two means of getting a listing of directory contents. One, FTP.nlst(), will return a list of the contents of a directory given a directory name as an argument. (It will return the name of a file if given a file name instead.) This is a robust way to list the contents of a directory but does not give any indication whether each item in the list is a file or directory. The other method is FTP.dir(), which gives a string formatted listing of the directory contents of the directory given as an argument (or of the file attributes, given a file name).

According to a previous question on Stack Overflow, parsing the results of dir() can be fragile (different servers may return different strings). I'm looking for some way to list just the directories contained within another directory over FTP, though. To the best of my knowledge, scraping for a d in the permissions part of the string is the only solution I've come up with, but I guess I can't guarantee that the permissions will appear in the same place between different servers. Is there a more robust solution to identifying directories over FTP?

解决方案

Unfortunately FTP doesn't have a command to list just folders so parsing the results you get from ftp.dir() would be 'best'.

A simple app assuming a standard result from ls (not a windows ftp)

from ftplib import FTP

ftp = FTP(host, user, passwd)
for r in ftp.dir():
    if r.upper().startswith('D'):
        print r[58:]  # Starting point

Standard FTP Commands

Custom FTP Commands

这篇关于通过FTP确定列表是否是Python中的目录或文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆