Python List Files in Directory: Methods & Examples
In Python, you can view files in a directory using either the os module or the glob module. Here are two methods:
- the bone
import os
# 指定目录路径
directory = '/path/to/directory'
# 列出目录中的所有文件和子目录
files = os.listdir(directory)
# 打印所有文件和子目录
for file in files:
print(file)
- sphere
import glob
# 指定目录路径
directory = '/path/to/directory'
# 使用glob.glob()函数获取目录下的所有文件
files = glob.glob(directory + '/*')
# 打印所有文件
for file in files:
print(file)
Both of these methods can be used to list all the files and subdirectories in the specified directory. You can choose one of the methods to use as needed.