Python Network Programming 简明教程

Python - Directory Listing

可以使用 Python 获取目录中的内容列表。我们可以制作一个程序,用于列出与运行 Python 的计算机位于同一台计算机上的目录的内容。我们也可以登录远程系统,列出远程目录的内容。

Python can be used to get the list of content from a directory. We can make program to list the content of directory which is in the same machine where python is running. We can also login to the remote system and list the content from the remote directory.

Listing Local Directory

在以下示例中,我们使用 listdir() 方法获取当前目录的内容。为了还指示内容的类型,如文件或目录,我们使用更多函数评估内容的性质。

In the below example we use the listdir() method to get the content of the current directory. To also indicate the type of the content like file or directory, we use more functions to evaluate the nature of the content.

for  name in os.listdir('.'):
    if os.path.isfile(name): print 'file: ', name
    elif os.path.isdir(name): print 'dir: ', name
    elif os.path.islink(name): print 'link: ', name
    else: print 'unknown', name

当我们运行以上程序时,我们得到以下输出:

When we run the above program, we get the following output −

file: abcl.htm
dir: allbooks
link: ulink

请注意,以上内容特定于运行 Python 程序的系统。结果将根据系统及其内容而有所不同。

Please note the content above is specific to the system where the python program was run. The result will vary depending on the system and its content.

Listing Remote Directory

我们可以使用 ftp 来访问远程系统,然后列出远程目录的内容。一旦建立连接,我们就可以使用命令以类似于列出本地目录的方式列出目录内容。

We can list the content of the remote directory by using ftp to access the remote system. Once the connection is established we can use commands that will list the directory contents in a way similar to the listing of local directories.

from ftplib import FTP
def main():
    ftp = FTP('ftp.ibiblio.org')
    ftp.login()
    ftp.cwd('pub/academic/biology/') # change to some other subject
    entries = ftp.nlst()
    ftp.quit()

    print(len(entries), "entries:")
    for entry in sorted(entries):
        print(entry)

if __name__ == '__main__':
    main()

当我们运行以上程序时,我们得到以下输出:

When we run the above program, we get the following output −

(6, 'entries:')
INDEX
README
acedb
dna-mutations
ecology+evolution
molbio