Get all file paths under the specified folder and the paths of subfolders containing files
import os
def read_files(directory):
for root, dirs, files in os.walk(directory):
for file_name in files:
file_path = os.path.join(root, file_name)
parent_directory = os.path.dirname(root) # Get the parent directory
# Specify the directory path
directory_path = '/path/to/directory'
# Call the function to read files from the directory and its subdirectories
read_files(directory_path)
If you need to return the result, you can return the obtained file path and folder path together in the form of a collection
import os
def read_files(directory):
result = set() # 创建一个空的集合
for root, dirs, files in os.walk(directory):
for file_name in files:
file_path = os.path.join(root, file_name)
parent_directory = os.path.dirname(root) # 获取父目录路径
# 将 file_path 和 parent_directory 添加到集合中
result.add((file_path, parent_directory))
return result
# 指定目录路径
directory_path = '/path/to/directory'
# 调用函数读取目录及其子目录中的文件,并获取结果集合
file_info_set = read_files(directory_path)
# 打印结果集合
for file_path, parent_directory in file_info_set:
print("File Path:", file_path)
print("Parent Directory:", parent_directory)
print() # 打印空行,用于分隔每个文件的信息