欢迎访问宙启技术站
智能推送

Python中如何使用list_directory()函数遍历目录内容

发布时间:2023-12-11 05:00:37

在Python中,可以使用os模块中的listdir()函数来遍历目录中的文件和子目录。listdir()函数返回指定目录中的文件和子目录列表。

下面是一个使用listdir()函数遍历目录内容的示例:

import os

def list_directory(path):
    # 使用listdir函数获取指定目录中的文件和子目录列表
    contents = os.listdir(path)

    for item in contents:
        item_path = os.path.join(path, item)
        if os.path.isfile(item_path):
            # 如果是文件,则直接打印
            print("File:", item_path)
        elif os.path.isdir(item_path):
            # 如果是子目录,则递归调用list_directory函数继续遍历
            print("Directory:", item_path)
            list_directory(item_path)

# 调用list_directory函数来遍历指定目录
list_directory("/path/to/directory")

在这个例子中,首先定义了一个list_directory()函数,该函数接收一个路径参数。接下来,使用os.listdir()函数获取指定目录中的内容并保存到contents变量中。然后通过一个循环遍历contents列表中的每个项。对于每个项,使用os.path.join()函数将路径和项连接起来,得到完整的路径。如果该项是一个文件,则直接打印文件路径。如果是一个子目录,则递归调用list_directory()函数来遍历子目录。

可以根据需要修改list_directory()函数的功能。例如,可以在函数中增加其他的操作,比如判断文件的大小、获取文件的创建时间等。

下面是一个具体的例子,展示如何使用list_directory()函数遍历目录,并输出文件的大小:

import os

def list_directory(path):
    contents = os.listdir(path)

    for item in contents:
        item_path = os.path.join(path, item)
        if os.path.isfile(item_path):
            # 如果是文件,则打印文件路径和文件大小
            file_size = os.path.getsize(item_path)
            print("File:", item_path, " Size:", file_size, "bytes")
        elif os.path.isdir(item_path):
            # 如果是子目录,则递归调用list_directory函数继续遍历
            print("Directory:", item_path)
            list_directory(item_path)

# 调用list_directory函数来遍历指定目录
list_directory("/path/to/directory")

在这个例子中,修改了list_directory()函数的逻辑,添加了os.path.getsize()函数来获取文件的大小,并将文件大小打印出来。

通过以上的例子,可以使用list_directory()函数来遍历目录中的文件和子目录,并实现自己的逻辑来处理这些文件和目录。