How can I display all the files in a directory using Python?

You can use the os module to list all files in a directory. The specific steps are as follows:

  1. I need to bring in the os package.
  2. show the directory contents
  3. List all the files in the specified directory.
  4. way
  5. Traverse the list of files obtained, determine whether each element is a file or a folder, and take the appropriate action.

Here is an example code that demonstrates how to list all files in a directory.

import os

def list_files(path):
    files = os.listdir(path)
    for file in files:
        file_path = os.path.join(path, file)
        if os.path.isfile(file_path):
            print("文件:", file)
        elif os.path.isdir(file_path):
            print("文件夹:", file)

# 列出当前目录下的所有文件
list_files(".")

This code will print out all the files and folders in the current directory individually.

bannerAds